Home | History | Annotate | Line # | Download | only in dist
serverloop.c revision 1.10
      1 /*	$NetBSD: serverloop.c,v 1.10 2015/04/03 23:58:19 christos Exp $	*/
      2 /* $OpenBSD: serverloop.c,v 1.178 2015/02/20 22:17:21 djm Exp $ */
      3 /*
      4  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      5  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      6  *                    All rights reserved
      7  * Server main loop for handling the interactive session.
      8  *
      9  * As far as I am concerned, the code I have written for this software
     10  * can be used freely for any purpose.  Any derived versions of this
     11  * software must be clearly marked as such, and if the derived work is
     12  * incompatible with the protocol description in the RFC file, it must be
     13  * called by a name other than "ssh" or "Secure Shell".
     14  *
     15  * SSH2 support by Markus Friedl.
     16  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
     17  *
     18  * Redistribution and use in source and binary forms, with or without
     19  * modification, are permitted provided that the following conditions
     20  * are met:
     21  * 1. Redistributions of source code must retain the above copyright
     22  *    notice, this list of conditions and the following disclaimer.
     23  * 2. Redistributions in binary form must reproduce the above copyright
     24  *    notice, this list of conditions and the following disclaimer in the
     25  *    documentation and/or other materials provided with the distribution.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include "includes.h"
     40 __RCSID("$NetBSD: serverloop.c,v 1.10 2015/04/03 23:58:19 christos Exp $");
     41 #include <sys/param.h>	/* MIN MAX */
     42 #include <sys/types.h>
     43 #include <sys/wait.h>
     44 #include <sys/socket.h>
     45 #include <sys/time.h>
     46 #include <sys/queue.h>
     47 
     48 #include <netinet/in.h>
     49 
     50 #include <errno.h>
     51 #include <fcntl.h>
     52 #include <pwd.h>
     53 #include <signal.h>
     54 #include <string.h>
     55 #include <termios.h>
     56 #include <unistd.h>
     57 #include <stdarg.h>
     58 
     59 #include "xmalloc.h"
     60 #include "packet.h"
     61 #include "buffer.h"
     62 #include "log.h"
     63 #include "misc.h"
     64 #include "servconf.h"
     65 #include "canohost.h"
     66 #include "sshpty.h"
     67 #include "channels.h"
     68 #include "compat.h"
     69 #include "ssh1.h"
     70 #include "ssh2.h"
     71 #include "key.h"
     72 #include "cipher.h"
     73 #include "kex.h"
     74 #include "hostfile.h"
     75 #include "auth.h"
     76 #include "session.h"
     77 #include "dispatch.h"
     78 #include "auth-options.h"
     79 #include "serverloop.h"
     80 #include "roaming.h"
     81 #include "ssherr.h"
     82 
     83 extern ServerOptions options;
     84 
     85 /* XXX */
     86 extern Authctxt *the_authctxt;
     87 extern int use_privsep;
     88 
     89 static Buffer stdin_buffer;	/* Buffer for stdin data. */
     90 static Buffer stdout_buffer;	/* Buffer for stdout data. */
     91 static Buffer stderr_buffer;	/* Buffer for stderr data. */
     92 static int fdin;		/* Descriptor for stdin (for writing) */
     93 static int fdout;		/* Descriptor for stdout (for reading);
     94 				   May be same number as fdin. */
     95 static int fderr;		/* Descriptor for stderr.  May be -1. */
     96 static u_long stdin_bytes = 0;	/* Number of bytes written to stdin. */
     97 static u_long stdout_bytes = 0;	/* Number of stdout bytes sent to client. */
     98 static u_long stderr_bytes = 0;	/* Number of stderr bytes sent to client. */
     99 static u_long fdout_bytes = 0;	/* Number of stdout bytes read from program. */
    100 static int stdin_eof = 0;	/* EOF message received from client. */
    101 static int fdout_eof = 0;	/* EOF encountered reading from fdout. */
    102 static int fderr_eof = 0;	/* EOF encountered readung from fderr. */
    103 static int fdin_is_tty = 0;	/* fdin points to a tty. */
    104 static int connection_in;	/* Connection to client (input). */
    105 static int connection_out;	/* Connection to client (output). */
    106 static int connection_closed = 0;	/* Connection to client closed. */
    107 static u_int buffer_high;	/* "Soft" max buffer size. */
    108 static int no_more_sessions = 0; /* Disallow further sessions. */
    109 
    110 /*
    111  * This SIGCHLD kludge is used to detect when the child exits.  The server
    112  * will exit after that, as soon as forwarded connections have terminated.
    113  */
    114 
    115 static volatile sig_atomic_t child_terminated = 0;	/* The child has terminated. */
    116 
    117 /* Cleanup on signals (!use_privsep case only) */
    118 static volatile sig_atomic_t received_sigterm = 0;
    119 
    120 /* prototypes */
    121 static void server_init_dispatch(void);
    122 
    123 /*
    124  * Returns current time in seconds from Jan 1, 1970 with the maximum
    125  * available resolution.
    126  */
    127 
    128 static double
    129 get_current_time(void)
    130 {
    131 	struct timeval tv;
    132 	gettimeofday(&tv, NULL);
    133 	return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
    134 }
    135 
    136 /*
    137  * we write to this pipe if a SIGCHLD is caught in order to avoid
    138  * the race between select() and child_terminated
    139  */
    140 static int notify_pipe[2];
    141 static void
    142 notify_setup(void)
    143 {
    144 	if (pipe(notify_pipe) < 0) {
    145 		error("pipe(notify_pipe) failed %s", strerror(errno));
    146 	} else if ((fcntl(notify_pipe[0], F_SETFD, FD_CLOEXEC) == -1) ||
    147 	    (fcntl(notify_pipe[1], F_SETFD, FD_CLOEXEC) == -1)) {
    148 		error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
    149 		close(notify_pipe[0]);
    150 		close(notify_pipe[1]);
    151 	} else {
    152 		set_nonblock(notify_pipe[0]);
    153 		set_nonblock(notify_pipe[1]);
    154 		return;
    155 	}
    156 	notify_pipe[0] = -1;	/* read end */
    157 	notify_pipe[1] = -1;	/* write end */
    158 }
    159 static void
    160 notify_parent(void)
    161 {
    162 	if (notify_pipe[1] != -1)
    163 		(void)write(notify_pipe[1], "", 1);
    164 }
    165 static void
    166 notify_prepare(fd_set *readset)
    167 {
    168 	if (notify_pipe[0] != -1)
    169 		FD_SET(notify_pipe[0], readset);
    170 }
    171 static void
    172 notify_done(fd_set *readset)
    173 {
    174 	char c;
    175 
    176 	if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
    177 		while (read(notify_pipe[0], &c, 1) != -1)
    178 			debug2("notify_done: reading");
    179 }
    180 
    181 /*ARGSUSED*/
    182 static void
    183 sigchld_handler(int sig)
    184 {
    185 	int save_errno = errno;
    186 	child_terminated = 1;
    187 	signal(SIGCHLD, sigchld_handler);
    188 	notify_parent();
    189 	errno = save_errno;
    190 }
    191 
    192 /*ARGSUSED*/
    193 static void
    194 sigterm_handler(int sig)
    195 {
    196 	received_sigterm = sig;
    197 }
    198 
    199 /*
    200  * Make packets from buffered stderr data, and buffer it for sending
    201  * to the client.
    202  */
    203 static void
    204 make_packets_from_stderr_data(void)
    205 {
    206 	u_int len;
    207 
    208 	/* Send buffered stderr data to the client. */
    209 	while (buffer_len(&stderr_buffer) > 0 &&
    210 	    packet_not_very_much_data_to_write()) {
    211 		len = buffer_len(&stderr_buffer);
    212 		if (packet_is_interactive()) {
    213 			if (len > 512)
    214 				len = 512;
    215 		} else {
    216 			/* Keep the packets at reasonable size. */
    217 			if (len > packet_get_maxsize())
    218 				len = packet_get_maxsize();
    219 		}
    220 		packet_start(SSH_SMSG_STDERR_DATA);
    221 		packet_put_string(buffer_ptr(&stderr_buffer), len);
    222 		packet_send();
    223 		buffer_consume(&stderr_buffer, len);
    224 		stderr_bytes += len;
    225 	}
    226 }
    227 
    228 /*
    229  * Make packets from buffered stdout data, and buffer it for sending to the
    230  * client.
    231  */
    232 static void
    233 make_packets_from_stdout_data(void)
    234 {
    235 	u_int len;
    236 
    237 	/* Send buffered stdout data to the client. */
    238 	while (buffer_len(&stdout_buffer) > 0 &&
    239 	    packet_not_very_much_data_to_write()) {
    240 		len = buffer_len(&stdout_buffer);
    241 		if (packet_is_interactive()) {
    242 			if (len > 512)
    243 				len = 512;
    244 		} else {
    245 			/* Keep the packets at reasonable size. */
    246 			if (len > packet_get_maxsize())
    247 				len = packet_get_maxsize();
    248 		}
    249 		packet_start(SSH_SMSG_STDOUT_DATA);
    250 		packet_put_string(buffer_ptr(&stdout_buffer), len);
    251 		packet_send();
    252 		buffer_consume(&stdout_buffer, len);
    253 		stdout_bytes += len;
    254 	}
    255 }
    256 
    257 static void
    258 client_alive_check(void)
    259 {
    260 	int channel_id;
    261 
    262 	/* timeout, check to see how many we have had */
    263 	if (packet_inc_alive_timeouts() > options.client_alive_count_max) {
    264 		logit("Timeout, client not responding.");
    265 		cleanup_exit(255);
    266 	}
    267 
    268 	/*
    269 	 * send a bogus global/channel request with "wantreply",
    270 	 * we should get back a failure
    271 	 */
    272 	if ((channel_id = channel_find_open()) == -1) {
    273 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
    274 		packet_put_cstring("keepalive (at) openssh.com");
    275 		packet_put_char(1);	/* boolean: want reply */
    276 	} else {
    277 		channel_request_start(channel_id, "keepalive (at) openssh.com", 1);
    278 	}
    279 	packet_send();
    280 }
    281 
    282 /*
    283  * Sleep in select() until we can do something.  This will initialize the
    284  * select masks.  Upon return, the masks will indicate which descriptors
    285  * have data or can accept data.  Optionally, a maximum time can be specified
    286  * for the duration of the wait (0 = infinite).
    287  */
    288 static void
    289 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
    290     u_int *nallocp, u_int64_t max_time_milliseconds)
    291 {
    292 	struct timeval tv, *tvp;
    293 	int ret;
    294 	time_t minwait_secs = 0;
    295 	int client_alive_scheduled = 0;
    296 
    297 	/* Allocate and update select() masks for channel descriptors. */
    298 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
    299 	    &minwait_secs, 0);
    300 
    301 	if (minwait_secs != 0)
    302 		max_time_milliseconds = MIN(max_time_milliseconds,
    303 		    (u_int)minwait_secs * 1000);
    304 
    305 	/*
    306 	 * if using client_alive, set the max timeout accordingly,
    307 	 * and indicate that this particular timeout was for client
    308 	 * alive by setting the client_alive_scheduled flag.
    309 	 *
    310 	 * this could be randomized somewhat to make traffic
    311 	 * analysis more difficult, but we're not doing it yet.
    312 	 */
    313 	if (compat20 &&
    314 	    max_time_milliseconds == 0 && options.client_alive_interval) {
    315 		client_alive_scheduled = 1;
    316 		max_time_milliseconds =
    317 		    (u_int64_t)options.client_alive_interval * 1000;
    318 	}
    319 
    320 	if (compat20) {
    321 #if 0
    322 		/* wrong: bad condition XXX */
    323 		if (channel_not_very_much_buffered_data())
    324 #endif
    325 		FD_SET(connection_in, *readsetp);
    326 	} else {
    327 		/*
    328 		 * Read packets from the client unless we have too much
    329 		 * buffered stdin or channel data.
    330 		 */
    331 		if (buffer_len(&stdin_buffer) < buffer_high &&
    332 		    channel_not_very_much_buffered_data())
    333 			FD_SET(connection_in, *readsetp);
    334 		/*
    335 		 * If there is not too much data already buffered going to
    336 		 * the client, try to get some more data from the program.
    337 		 */
    338 		if (packet_not_very_much_data_to_write()) {
    339 			if (!fdout_eof)
    340 				FD_SET(fdout, *readsetp);
    341 			if (!fderr_eof)
    342 				FD_SET(fderr, *readsetp);
    343 		}
    344 		/*
    345 		 * If we have buffered data, try to write some of that data
    346 		 * to the program.
    347 		 */
    348 		if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
    349 			FD_SET(fdin, *writesetp);
    350 	}
    351 	notify_prepare(*readsetp);
    352 
    353 	/*
    354 	 * If we have buffered packet data going to the client, mark that
    355 	 * descriptor.
    356 	 */
    357 	if (packet_have_data_to_write())
    358 		FD_SET(connection_out, *writesetp);
    359 
    360 	/*
    361 	 * If child has terminated and there is enough buffer space to read
    362 	 * from it, then read as much as is available and exit.
    363 	 */
    364 	if (child_terminated && packet_not_very_much_data_to_write())
    365 		if (max_time_milliseconds == 0 || client_alive_scheduled)
    366 			max_time_milliseconds = 100;
    367 
    368 	if (max_time_milliseconds == 0)
    369 		tvp = NULL;
    370 	else {
    371 		tv.tv_sec = max_time_milliseconds / 1000;
    372 		tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
    373 		tvp = &tv;
    374 	}
    375 
    376 	/* Wait for something to happen, or the timeout to expire. */
    377 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
    378 
    379 	if (ret == -1) {
    380 		memset(*readsetp, 0, *nallocp);
    381 		memset(*writesetp, 0, *nallocp);
    382 		if (errno != EINTR)
    383 			error("select: %.100s", strerror(errno));
    384 	} else if (ret == 0 && client_alive_scheduled)
    385 		client_alive_check();
    386 
    387 	notify_done(*readsetp);
    388 }
    389 
    390 /*
    391  * Processes input from the client and the program.  Input data is stored
    392  * in buffers and processed later.
    393  */
    394 static void
    395 process_input(fd_set *readset)
    396 {
    397 	int len;
    398 	char buf[16384];
    399 
    400 	/* Read and buffer any input data from the client. */
    401 	if (FD_ISSET(connection_in, readset)) {
    402 		int cont = 0;
    403 		len = roaming_read(connection_in, buf, sizeof(buf), &cont);
    404 		if (len == 0) {
    405 			if (cont)
    406 				return;
    407 			verbose("Connection closed by %.100s",
    408 			    get_remote_ipaddr());
    409 			connection_closed = 1;
    410 			if (compat20)
    411 				return;
    412 			cleanup_exit(255);
    413 		} else if (len < 0) {
    414 			if (errno != EINTR && errno != EAGAIN) {
    415 				verbose("Read error from remote host "
    416 				    "%.100s: %.100s",
    417 				    get_remote_ipaddr(), strerror(errno));
    418 				cleanup_exit(255);
    419 			}
    420 		} else {
    421 			/* Buffer any received data. */
    422 			packet_process_incoming(buf, len);
    423 			fdout_bytes += len;
    424 		}
    425 	}
    426 	if (compat20)
    427 		return;
    428 
    429 	/* Read and buffer any available stdout data from the program. */
    430 	if (!fdout_eof && FD_ISSET(fdout, readset)) {
    431 		len = read(fdout, buf, sizeof(buf));
    432 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
    433 			/* do nothing */
    434 		} else if (len <= 0) {
    435 			fdout_eof = 1;
    436 		} else {
    437 			buffer_append(&stdout_buffer, buf, len);
    438 			debug ("FD out now: %ld", fdout_bytes);
    439 			fdout_bytes += len;
    440 		}
    441 	}
    442 	/* Read and buffer any available stderr data from the program. */
    443 	if (!fderr_eof && FD_ISSET(fderr, readset)) {
    444 		len = read(fderr, buf, sizeof(buf));
    445 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
    446 			/* do nothing */
    447 		} else if (len <= 0) {
    448 			fderr_eof = 1;
    449 		} else {
    450 			buffer_append(&stderr_buffer, buf, len);
    451 		}
    452 	}
    453 }
    454 
    455 /*
    456  * Sends data from internal buffers to client program stdin.
    457  */
    458 static void
    459 process_output(fd_set *writeset)
    460 {
    461 	struct termios tio;
    462 	u_char *data;
    463 	u_int dlen;
    464 	int len;
    465 
    466 	/* Write buffered data to program stdin. */
    467 	if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
    468 		data = buffer_ptr(&stdin_buffer);
    469 		dlen = buffer_len(&stdin_buffer);
    470 		len = write(fdin, data, dlen);
    471 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
    472 			/* do nothing */
    473 		} else if (len <= 0) {
    474 			if (fdin != fdout)
    475 				close(fdin);
    476 			else
    477 				shutdown(fdin, SHUT_WR); /* We will no longer send. */
    478 			fdin = -1;
    479 		} else {
    480 			/* Successful write. */
    481 			if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
    482 			    tcgetattr(fdin, &tio) == 0 &&
    483 			    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
    484 				/*
    485 				 * Simulate echo to reduce the impact of
    486 				 * traffic analysis
    487 				 */
    488 				packet_send_ignore(len);
    489 				packet_send();
    490 			}
    491 			/* Consume the data from the buffer. */
    492 			buffer_consume(&stdin_buffer, len);
    493 			/* Update the count of bytes written to the program. */
    494 			stdin_bytes += len;
    495 		}
    496 	}
    497 	/* Send any buffered packet data to the client. */
    498 	if (FD_ISSET(connection_out, writeset))
    499 		stdin_bytes += packet_write_poll();
    500 }
    501 
    502 /*
    503  * Wait until all buffered output has been sent to the client.
    504  * This is used when the program terminates.
    505  */
    506 static void
    507 drain_output(void)
    508 {
    509 	/* Send any buffered stdout data to the client. */
    510 	if (buffer_len(&stdout_buffer) > 0) {
    511 		packet_start(SSH_SMSG_STDOUT_DATA);
    512 		packet_put_string(buffer_ptr(&stdout_buffer),
    513 				  buffer_len(&stdout_buffer));
    514 		packet_send();
    515 		/* Update the count of sent bytes. */
    516 		stdout_bytes += buffer_len(&stdout_buffer);
    517 	}
    518 	/* Send any buffered stderr data to the client. */
    519 	if (buffer_len(&stderr_buffer) > 0) {
    520 		packet_start(SSH_SMSG_STDERR_DATA);
    521 		packet_put_string(buffer_ptr(&stderr_buffer),
    522 				  buffer_len(&stderr_buffer));
    523 		packet_send();
    524 		/* Update the count of sent bytes. */
    525 		stderr_bytes += buffer_len(&stderr_buffer);
    526 	}
    527 	/* Wait until all buffered data has been written to the client. */
    528 	packet_write_wait();
    529 }
    530 
    531 static void
    532 process_buffered_input_packets(void)
    533 {
    534 	dispatch_run(DISPATCH_NONBLOCK, NULL, active_state);
    535 }
    536 
    537 /*
    538  * Performs the interactive session.  This handles data transmission between
    539  * the client and the program.  Note that the notion of stdin, stdout, and
    540  * stderr in this function is sort of reversed: this function writes to
    541  * stdin (of the child program), and reads from stdout and stderr (of the
    542  * child program).
    543  */
    544 void
    545 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
    546 {
    547 	fd_set *readset = NULL, *writeset = NULL;
    548 	int max_fd = 0;
    549 	u_int nalloc = 0;
    550 	int wait_status;	/* Status returned by wait(). */
    551 	pid_t wait_pid;		/* pid returned by wait(). */
    552 	int waiting_termination = 0;	/* Have displayed waiting close message. */
    553 	u_int64_t max_time_milliseconds;
    554 	u_int previous_stdout_buffer_bytes;
    555 	u_int stdout_buffer_bytes;
    556 	int type;
    557 
    558 	debug("Entering interactive session.");
    559 
    560 	/* Initialize the SIGCHLD kludge. */
    561 	child_terminated = 0;
    562 	signal(SIGCHLD, sigchld_handler);
    563 
    564 	if (!use_privsep) {
    565 		signal(SIGTERM, sigterm_handler);
    566 		signal(SIGINT, sigterm_handler);
    567 		signal(SIGQUIT, sigterm_handler);
    568 	}
    569 
    570 	/* Initialize our global variables. */
    571 	fdin = fdin_arg;
    572 	fdout = fdout_arg;
    573 	fderr = fderr_arg;
    574 
    575 	/* nonblocking IO */
    576 	set_nonblock(fdin);
    577 	set_nonblock(fdout);
    578 	/* we don't have stderr for interactive terminal sessions, see below */
    579 	if (fderr != -1)
    580 		set_nonblock(fderr);
    581 
    582 	if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
    583 		fdin_is_tty = 1;
    584 
    585 	connection_in = packet_get_connection_in();
    586 	connection_out = packet_get_connection_out();
    587 
    588 	notify_setup();
    589 
    590 	previous_stdout_buffer_bytes = 0;
    591 
    592 	/* Set approximate I/O buffer size. */
    593 	if (packet_is_interactive())
    594 		buffer_high = 4096;
    595 	else
    596 		buffer_high = 64 * 1024;
    597 
    598 #if 0
    599 	/* Initialize max_fd to the maximum of the known file descriptors. */
    600 	max_fd = MAX(connection_in, connection_out);
    601 	max_fd = MAX(max_fd, fdin);
    602 	max_fd = MAX(max_fd, fdout);
    603 	if (fderr != -1)
    604 		max_fd = MAX(max_fd, fderr);
    605 #endif
    606 
    607 	/* Initialize Initialize buffers. */
    608 	buffer_init(&stdin_buffer);
    609 	buffer_init(&stdout_buffer);
    610 	buffer_init(&stderr_buffer);
    611 
    612 	/*
    613 	 * If we have no separate fderr (which is the case when we have a pty
    614 	 * - there we cannot make difference between data sent to stdout and
    615 	 * stderr), indicate that we have seen an EOF from stderr.  This way
    616 	 * we don't need to check the descriptor everywhere.
    617 	 */
    618 	if (fderr == -1)
    619 		fderr_eof = 1;
    620 
    621 	server_init_dispatch();
    622 
    623 	/* Main loop of the server for the interactive session mode. */
    624 	for (;;) {
    625 
    626 		/* Process buffered packets from the client. */
    627 		process_buffered_input_packets();
    628 
    629 		/*
    630 		 * If we have received eof, and there is no more pending
    631 		 * input data, cause a real eof by closing fdin.
    632 		 */
    633 		if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
    634 			if (fdin != fdout)
    635 				close(fdin);
    636 			else
    637 				shutdown(fdin, SHUT_WR); /* We will no longer send. */
    638 			fdin = -1;
    639 		}
    640 		/* Make packets from buffered stderr data to send to the client. */
    641 		make_packets_from_stderr_data();
    642 
    643 		/*
    644 		 * Make packets from buffered stdout data to send to the
    645 		 * client. If there is very little to send, this arranges to
    646 		 * not send them now, but to wait a short while to see if we
    647 		 * are getting more data. This is necessary, as some systems
    648 		 * wake up readers from a pty after each separate character.
    649 		 */
    650 		max_time_milliseconds = 0;
    651 		stdout_buffer_bytes = buffer_len(&stdout_buffer);
    652 		if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
    653 		    stdout_buffer_bytes != previous_stdout_buffer_bytes) {
    654 			/* try again after a while */
    655 			max_time_milliseconds = 10;
    656 		} else {
    657 			/* Send it now. */
    658 			make_packets_from_stdout_data();
    659 		}
    660 		previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
    661 
    662 		/* Send channel data to the client. */
    663 		if (packet_not_very_much_data_to_write())
    664 			channel_output_poll();
    665 
    666 		/*
    667 		 * Bail out of the loop if the program has closed its output
    668 		 * descriptors, and we have no more data to send to the
    669 		 * client, and there is no pending buffered data.
    670 		 */
    671 		if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
    672 		    buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
    673 			if (!channel_still_open())
    674 				break;
    675 			if (!waiting_termination) {
    676 				const char *s = "Waiting for forwarded connections to terminate...\r\n";
    677 				char *cp;
    678 				waiting_termination = 1;
    679 				buffer_append(&stderr_buffer, s, strlen(s));
    680 
    681 				/* Display list of open channels. */
    682 				cp = channel_open_message();
    683 				buffer_append(&stderr_buffer, cp, strlen(cp));
    684 				free(cp);
    685 			}
    686 		}
    687 		max_fd = MAX(connection_in, connection_out);
    688 		max_fd = MAX(max_fd, fdin);
    689 		max_fd = MAX(max_fd, fdout);
    690 		max_fd = MAX(max_fd, fderr);
    691 		max_fd = MAX(max_fd, notify_pipe[0]);
    692 
    693 		/* Sleep in select() until we can do something. */
    694 		wait_until_can_do_something(&readset, &writeset, &max_fd,
    695 		    &nalloc, max_time_milliseconds);
    696 
    697 		if (received_sigterm) {
    698 			logit("Exiting on signal %d", (int)received_sigterm);
    699 			/* Clean up sessions, utmp, etc. */
    700 			cleanup_exit(255);
    701 		}
    702 
    703 		/* Process any channel events. */
    704 		channel_after_select(readset, writeset);
    705 
    706 		/* Process input from the client and from program stdout/stderr. */
    707 		process_input(readset);
    708 
    709 		/* Process output to the client and to program stdin. */
    710 		process_output(writeset);
    711 	}
    712 	free(readset);
    713 	free(writeset);
    714 
    715 	/* Cleanup and termination code. */
    716 
    717 	/* Wait until all output has been sent to the client. */
    718 	drain_output();
    719 
    720 	debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
    721 	    stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
    722 
    723 	/* Free and clear the buffers. */
    724 	buffer_free(&stdin_buffer);
    725 	buffer_free(&stdout_buffer);
    726 	buffer_free(&stderr_buffer);
    727 
    728 	/* Close the file descriptors. */
    729 	if (fdout != -1)
    730 		close(fdout);
    731 	fdout = -1;
    732 	fdout_eof = 1;
    733 	if (fderr != -1)
    734 		close(fderr);
    735 	fderr = -1;
    736 	fderr_eof = 1;
    737 	if (fdin != -1)
    738 		close(fdin);
    739 	fdin = -1;
    740 
    741 	channel_free_all();
    742 
    743 	/* We no longer want our SIGCHLD handler to be called. */
    744 	signal(SIGCHLD, SIG_DFL);
    745 
    746 	while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
    747 		if (errno != EINTR)
    748 			packet_disconnect("wait: %.100s", strerror(errno));
    749 	if (wait_pid != pid)
    750 		error("Strange, wait returned pid %ld, expected %ld",
    751 		    (long)wait_pid, (long)pid);
    752 
    753 	/* Check if it exited normally. */
    754 	if (WIFEXITED(wait_status)) {
    755 		/* Yes, normal exit.  Get exit status and send it to the client. */
    756 		debug("Command exited with status %d.", WEXITSTATUS(wait_status));
    757 		packet_start(SSH_SMSG_EXITSTATUS);
    758 		packet_put_int(WEXITSTATUS(wait_status));
    759 		packet_send();
    760 		packet_write_wait();
    761 
    762 		/*
    763 		 * Wait for exit confirmation.  Note that there might be
    764 		 * other packets coming before it; however, the program has
    765 		 * already died so we just ignore them.  The client is
    766 		 * supposed to respond with the confirmation when it receives
    767 		 * the exit status.
    768 		 */
    769 		do {
    770 			type = packet_read();
    771 		}
    772 		while (type != SSH_CMSG_EXIT_CONFIRMATION);
    773 
    774 		debug("Received exit confirmation.");
    775 		return;
    776 	}
    777 	/* Check if the program terminated due to a signal. */
    778 	if (WIFSIGNALED(wait_status))
    779 		packet_disconnect("Command terminated on signal %d.",
    780 				  WTERMSIG(wait_status));
    781 
    782 	/* Some weird exit cause.  Just exit. */
    783 	packet_disconnect("wait returned status %04x.", wait_status);
    784 	/* NOTREACHED */
    785 }
    786 
    787 static void
    788 collect_children(void)
    789 {
    790 	pid_t pid;
    791 	sigset_t oset, nset;
    792 	int status;
    793 
    794 	/* block SIGCHLD while we check for dead children */
    795 	sigemptyset(&nset);
    796 	sigaddset(&nset, SIGCHLD);
    797 	sigprocmask(SIG_BLOCK, &nset, &oset);
    798 	if (child_terminated) {
    799 		debug("Received SIGCHLD.");
    800 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
    801 		    (pid < 0 && errno == EINTR))
    802 			if (pid > 0)
    803 				session_close_by_pid(pid, status);
    804 		child_terminated = 0;
    805 	}
    806 	sigprocmask(SIG_SETMASK, &oset, NULL);
    807 }
    808 
    809 void
    810 server_loop2(Authctxt *authctxt)
    811 {
    812 	fd_set *readset = NULL, *writeset = NULL;
    813 	int rekeying = 0, max_fd;
    814 	u_int nalloc = 0;
    815 	u_int64_t rekey_timeout_ms = 0;
    816 	double start_time, total_time;
    817 
    818 	debug("Entering interactive session for SSH2.");
    819 	start_time = get_current_time();
    820 
    821 	signal(SIGCHLD, sigchld_handler);
    822 	child_terminated = 0;
    823 	connection_in = packet_get_connection_in();
    824 	connection_out = packet_get_connection_out();
    825 
    826 	if (!use_privsep) {
    827 		signal(SIGTERM, sigterm_handler);
    828 		signal(SIGINT, sigterm_handler);
    829 		signal(SIGQUIT, sigterm_handler);
    830 	}
    831 
    832 	notify_setup();
    833 
    834 	max_fd = MAX(connection_in, connection_out);
    835 	max_fd = MAX(max_fd, notify_pipe[0]);
    836 
    837 	server_init_dispatch();
    838 
    839 	for (;;) {
    840 		process_buffered_input_packets();
    841 
    842 		rekeying = (active_state->kex != NULL && !active_state->kex->done);
    843 
    844 		if (!rekeying && packet_not_very_much_data_to_write())
    845 			channel_output_poll();
    846 		if (options.rekey_interval > 0 && compat20 && !rekeying)
    847 			rekey_timeout_ms = packet_get_rekey_timeout() * 1000;
    848 		else
    849 			rekey_timeout_ms = 0;
    850 
    851 		wait_until_can_do_something(&readset, &writeset, &max_fd,
    852 		    &nalloc, rekey_timeout_ms);
    853 
    854 		if (received_sigterm) {
    855 			logit("Exiting on signal %d", (int)received_sigterm);
    856 			/* Clean up sessions, utmp, etc. */
    857 			cleanup_exit(255);
    858 		}
    859 
    860 		collect_children();
    861 		if (!rekeying) {
    862 			channel_after_select(readset, writeset);
    863 			if (packet_need_rekeying()) {
    864 				debug("need rekeying");
    865 				active_state->kex->done = 0;
    866 				kex_send_kexinit(active_state);
    867 			}
    868 		}
    869 		process_input(readset);
    870 		if (connection_closed)
    871 			break;
    872 		process_output(writeset);
    873 	}
    874 	collect_children();
    875 
    876 	free(readset);
    877 	free(writeset);
    878 
    879 	/* free all channels, no more reads and writes */
    880 	channel_free_all();
    881 
    882 	/* free remaining sessions, e.g. remove wtmp entries */
    883 	session_destroy_all(NULL);
    884 	total_time = get_current_time() - start_time;
    885 	logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
    886 	      get_remote_ipaddr(), get_remote_port(),
    887 	      stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time,
    888 	      fdout_bytes / total_time);
    889 }
    890 
    891 static int
    892 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
    893 {
    894 	debug("Got %d/%u for keepalive", type, seq);
    895 	/*
    896 	 * reset timeout, since we got a sane answer from the client.
    897 	 * even if this was generated by something other than
    898 	 * the bogus CHANNEL_REQUEST we send for keepalives.
    899 	 */
    900 	packet_set_alive_timeouts(0);
    901 	return 0;
    902 }
    903 
    904 static int
    905 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
    906 {
    907 	char *data;
    908 	u_int data_len;
    909 
    910 	/* Stdin data from the client.  Append it to the buffer. */
    911 	/* Ignore any data if the client has closed stdin. */
    912 	if (fdin == -1)
    913 		return 0;
    914 	data = packet_get_string(&data_len);
    915 	packet_check_eom();
    916 	buffer_append(&stdin_buffer, data, data_len);
    917 	explicit_bzero(data, data_len);
    918 	free(data);
    919 	return 0;
    920 }
    921 
    922 static int
    923 server_input_eof(int type, u_int32_t seq, void *ctxt)
    924 {
    925 	/*
    926 	 * Eof from the client.  The stdin descriptor to the
    927 	 * program will be closed when all buffered data has
    928 	 * drained.
    929 	 */
    930 	debug("EOF received for stdin.");
    931 	packet_check_eom();
    932 	stdin_eof = 1;
    933 	return 0;
    934 }
    935 
    936 static int
    937 server_input_window_size(int type, u_int32_t seq, void *ctxt)
    938 {
    939 	u_int row = packet_get_int();
    940 	u_int col = packet_get_int();
    941 	u_int xpixel = packet_get_int();
    942 	u_int ypixel = packet_get_int();
    943 
    944 	debug("Window change received.");
    945 	packet_check_eom();
    946 	if (fdin != -1)
    947 		pty_change_window_size(fdin, row, col, xpixel, ypixel);
    948 	return 0;
    949 }
    950 
    951 static Channel *
    952 server_request_direct_tcpip(void)
    953 {
    954 	Channel *c = NULL;
    955 	char *target, *originator;
    956 	u_short target_port, originator_port;
    957 
    958 	target = packet_get_string(NULL);
    959 	target_port = packet_get_int();
    960 	originator = packet_get_string(NULL);
    961 	originator_port = packet_get_int();
    962 	packet_check_eom();
    963 
    964 	debug("server_request_direct_tcpip: originator %s port %d, target %s "
    965 	    "port %d", originator, originator_port, target, target_port);
    966 
    967 	/* XXX fine grained permissions */
    968 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
    969 	    !no_port_forwarding_flag) {
    970 		c = channel_connect_to_port(target, target_port,
    971 		    "direct-tcpip", "direct-tcpip");
    972 	} else {
    973 		logit("refused local port forward: "
    974 		    "originator %s port %d, target %s port %d",
    975 		    originator, originator_port, target, target_port);
    976 	}
    977 
    978 	free(originator);
    979 	free(target);
    980 
    981 	return c;
    982 }
    983 
    984 static Channel *
    985 server_request_direct_streamlocal(void)
    986 {
    987 	Channel *c = NULL;
    988 	char *target, *originator;
    989 	u_short originator_port;
    990 
    991 	target = packet_get_string(NULL);
    992 	originator = packet_get_string(NULL);
    993 	originator_port = packet_get_int();
    994 	packet_check_eom();
    995 
    996 	debug("server_request_direct_streamlocal: originator %s port %d, target %s",
    997 	    originator, originator_port, target);
    998 
    999 	/* XXX fine grained permissions */
   1000 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
   1001 	    !no_port_forwarding_flag) {
   1002 		c = channel_connect_to_path(target,
   1003 		    "direct-streamlocal (at) openssh.com", "direct-streamlocal");
   1004 	} else {
   1005 		logit("refused streamlocal port forward: "
   1006 		    "originator %s port %d, target %s",
   1007 		    originator, originator_port, target);
   1008 	}
   1009 
   1010 	free(originator);
   1011 	free(target);
   1012 
   1013 	return c;
   1014 }
   1015 
   1016 static Channel *
   1017 server_request_tun(void)
   1018 {
   1019 	Channel *c = NULL;
   1020 	int mode, tun;
   1021 	int sock;
   1022 
   1023 	mode = packet_get_int();
   1024 	switch (mode) {
   1025 	case SSH_TUNMODE_POINTOPOINT:
   1026 	case SSH_TUNMODE_ETHERNET:
   1027 		break;
   1028 	default:
   1029 		packet_send_debug("Unsupported tunnel device mode.");
   1030 		return NULL;
   1031 	}
   1032 	if ((options.permit_tun & mode) == 0) {
   1033 		packet_send_debug("Server has rejected tunnel device "
   1034 		    "forwarding");
   1035 		return NULL;
   1036 	}
   1037 
   1038 	tun = packet_get_int();
   1039 	if (forced_tun_device != -1) {
   1040 		if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
   1041 			goto done;
   1042 		tun = forced_tun_device;
   1043 	}
   1044 	sock = tun_open(tun, mode);
   1045 	if (sock < 0)
   1046 		goto done;
   1047 	if (options.hpn_disabled)
   1048 	c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
   1049 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
   1050 	else
   1051 		c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
   1052 		    options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
   1053 	c->datagram = 1;
   1054 
   1055  done:
   1056 	if (c == NULL)
   1057 		packet_send_debug("Failed to open the tunnel device.");
   1058 	return c;
   1059 }
   1060 
   1061 static Channel *
   1062 server_request_session(void)
   1063 {
   1064 	Channel *c;
   1065 
   1066 	debug("input_session_request");
   1067 	packet_check_eom();
   1068 
   1069 	if (no_more_sessions) {
   1070 		packet_disconnect("Possible attack: attempt to open a session "
   1071 		    "after additional sessions disabled");
   1072 	}
   1073 
   1074 	/*
   1075 	 * A server session has no fd to read or write until a
   1076 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
   1077 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
   1078 	 * CHANNEL_REQUEST messages is registered.
   1079 	 */
   1080 	c = channel_new("session", SSH_CHANNEL_LARVAL,
   1081 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
   1082 	    0, "server-session", 1);
   1083 	if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled))
   1084 		c->dynamic_window = 1;
   1085 	if (session_open(the_authctxt, c->self) != 1) {
   1086 		debug("session open failed, free channel %d", c->self);
   1087 		channel_free(c);
   1088 		return NULL;
   1089 	}
   1090 	channel_register_cleanup(c->self, session_close_by_channel, 0);
   1091 	return c;
   1092 }
   1093 
   1094 static int
   1095 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
   1096 {
   1097 	Channel *c = NULL;
   1098 	char *ctype;
   1099 	int rchan;
   1100 	u_int rmaxpack, rwindow, len;
   1101 
   1102 	ctype = packet_get_string(&len);
   1103 	rchan = packet_get_int();
   1104 	rwindow = packet_get_int();
   1105 	rmaxpack = packet_get_int();
   1106 
   1107 	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
   1108 	    ctype, rchan, rwindow, rmaxpack);
   1109 
   1110 	if (strcmp(ctype, "session") == 0) {
   1111 		c = server_request_session();
   1112 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
   1113 		c = server_request_direct_tcpip();
   1114 	} else if (strcmp(ctype, "direct-streamlocal (at) openssh.com") == 0) {
   1115 		c = server_request_direct_streamlocal();
   1116 	} else if (strcmp(ctype, "tun (at) openssh.com") == 0) {
   1117 		c = server_request_tun();
   1118 	}
   1119 	if (c != NULL) {
   1120 		debug("server_input_channel_open: confirm %s", ctype);
   1121 		c->remote_id = rchan;
   1122 		c->remote_window = rwindow;
   1123 		c->remote_maxpacket = rmaxpack;
   1124 		if (c->type != SSH_CHANNEL_CONNECTING) {
   1125 			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
   1126 			packet_put_int(c->remote_id);
   1127 			packet_put_int(c->self);
   1128 			packet_put_int(c->local_window);
   1129 			packet_put_int(c->local_maxpacket);
   1130 			packet_send();
   1131 		}
   1132 	} else {
   1133 		debug("server_input_channel_open: failure %s", ctype);
   1134 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
   1135 		packet_put_int(rchan);
   1136 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
   1137 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
   1138 			packet_put_cstring("open failed");
   1139 			packet_put_cstring("");
   1140 		}
   1141 		packet_send();
   1142 	}
   1143 	free(ctype);
   1144 	return 0;
   1145 }
   1146 
   1147 static int
   1148 server_input_hostkeys_prove(struct sshbuf **respp)
   1149 {
   1150 	struct ssh *ssh = active_state; /* XXX */
   1151 	struct sshbuf *resp = NULL;
   1152 	struct sshbuf *sigbuf = NULL;
   1153 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
   1154 	int r, ndx, success = 0;
   1155 	const u_char *blob;
   1156 	u_char *sig = 0;
   1157 	size_t blen, slen;
   1158 
   1159 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
   1160 		fatal("%s: sshbuf_new", __func__);
   1161 
   1162 	while (ssh_packet_remaining(ssh) > 0) {
   1163 		sshkey_free(key);
   1164 		key = NULL;
   1165 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
   1166 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
   1167 			error("%s: couldn't parse key: %s",
   1168 			    __func__, ssh_err(r));
   1169 			goto out;
   1170 		}
   1171 		/*
   1172 		 * Better check that this is actually one of our hostkeys
   1173 		 * before attempting to sign anything with it.
   1174 		 */
   1175 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
   1176 			error("%s: unknown host %s key",
   1177 			    __func__, sshkey_type(key));
   1178 			goto out;
   1179 		}
   1180 		/*
   1181 		 * XXX refactor: make kex->sign just use an index rather
   1182 		 * than passing in public and private keys
   1183 		 */
   1184 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
   1185 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
   1186 			error("%s: can't retrieve hostkey %d", __func__, ndx);
   1187 			goto out;
   1188 		}
   1189 		sshbuf_reset(sigbuf);
   1190 		free(sig);
   1191 		sig = NULL;
   1192 		if ((r = sshbuf_put_cstring(sigbuf,
   1193 		    "hostkeys-prove-00 (at) openssh.com")) != 0 ||
   1194 		    (r = sshbuf_put_string(sigbuf,
   1195 		    ssh->kex->session_id, ssh->kex->session_id_len)) != 0 ||
   1196 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
   1197 		    (r = ssh->kex->sign(key_prv, key_pub, &sig, &slen,
   1198 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), 0)) != 0 ||
   1199 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
   1200 			error("%s: couldn't prepare signature: %s",
   1201 			    __func__, ssh_err(r));
   1202 			goto out;
   1203 		}
   1204 	}
   1205 	/* Success */
   1206 	*respp = resp;
   1207 	resp = NULL; /* don't free it */
   1208 	success = 1;
   1209  out:
   1210 	free(sig);
   1211 	sshbuf_free(resp);
   1212 	sshbuf_free(sigbuf);
   1213 	sshkey_free(key);
   1214 	return success;
   1215 }
   1216 
   1217 static int
   1218 server_input_global_request(int type, u_int32_t seq, void *ctxt)
   1219 {
   1220 	char *rtype;
   1221 	int want_reply;
   1222 	int r, success = 0, allocated_listen_port = 0;
   1223 	struct sshbuf *resp = NULL;
   1224 
   1225 	rtype = packet_get_string(NULL);
   1226 	want_reply = packet_get_char();
   1227 	debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
   1228 
   1229 	/* -R style forwarding */
   1230 	if (strcmp(rtype, "tcpip-forward") == 0) {
   1231 		struct passwd *pw;
   1232 		struct Forward fwd;
   1233 
   1234 		pw = the_authctxt->pw;
   1235 		if (pw == NULL || !the_authctxt->valid)
   1236 			fatal("server_input_global_request: no/invalid user");
   1237 		memset(&fwd, 0, sizeof(fwd));
   1238 		fwd.listen_host = packet_get_string(NULL);
   1239 		fwd.listen_port = (u_short)packet_get_int();
   1240 		debug("server_input_global_request: tcpip-forward listen %s port %d",
   1241 		    fwd.listen_host, fwd.listen_port);
   1242 
   1243 		/* check permissions */
   1244 		if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
   1245 		    no_port_forwarding_flag ||
   1246 		    (!want_reply && fwd.listen_port == 0) ||
   1247 		    (fwd.listen_port != 0 && fwd.listen_port < IPPORT_RESERVED &&
   1248 		    pw->pw_uid != 0)) {
   1249 			success = 0;
   1250 			packet_send_debug("Server has disabled port forwarding.");
   1251 		} else {
   1252 			/* Start listening on the port */
   1253 			success = channel_setup_remote_fwd_listener(&fwd,
   1254 			    &allocated_listen_port, &options.fwd_opts);
   1255 		}
   1256 		free(fwd.listen_host);
   1257 		if ((resp = sshbuf_new()) == NULL)
   1258 			fatal("%s: sshbuf_new", __func__);
   1259 		if ((r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
   1260 			fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
   1261 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
   1262 		struct Forward fwd;
   1263 
   1264 		memset(&fwd, 0, sizeof(fwd));
   1265 		fwd.listen_host = packet_get_string(NULL);
   1266 		fwd.listen_port = (u_short)packet_get_int();
   1267 		debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
   1268 		    fwd.listen_host, fwd.listen_port);
   1269 
   1270 		success = channel_cancel_rport_listener(&fwd);
   1271 		free(fwd.listen_host);
   1272 	} else if (strcmp(rtype, "streamlocal-forward (at) openssh.com") == 0) {
   1273 		struct Forward fwd;
   1274 
   1275 		memset(&fwd, 0, sizeof(fwd));
   1276 		fwd.listen_path = packet_get_string(NULL);
   1277 		debug("server_input_global_request: streamlocal-forward listen path %s",
   1278 		    fwd.listen_path);
   1279 
   1280 		/* check permissions */
   1281 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
   1282 		    || no_port_forwarding_flag) {
   1283 			success = 0;
   1284 			packet_send_debug("Server has disabled port forwarding.");
   1285 		} else {
   1286 			/* Start listening on the socket */
   1287 			success = channel_setup_remote_fwd_listener(
   1288 			    &fwd, NULL, &options.fwd_opts);
   1289 		}
   1290 		free(fwd.listen_path);
   1291 	} else if (strcmp(rtype, "cancel-streamlocal-forward (at) openssh.com") == 0) {
   1292 		struct Forward fwd;
   1293 
   1294 		memset(&fwd, 0, sizeof(fwd));
   1295 		fwd.listen_path = packet_get_string(NULL);
   1296 		debug("%s: cancel-streamlocal-forward path %s", __func__,
   1297 		    fwd.listen_path);
   1298 
   1299 		success = channel_cancel_rport_listener(&fwd);
   1300 		free(fwd.listen_path);
   1301 	} else if (strcmp(rtype, "no-more-sessions (at) openssh.com") == 0) {
   1302 		no_more_sessions = 1;
   1303 		success = 1;
   1304 	} else if (strcmp(rtype, "hostkeys-prove-00 (at) openssh.com") == 0) {
   1305 		success = server_input_hostkeys_prove(&resp);
   1306 	}
   1307 	if (want_reply) {
   1308 		packet_start(success ?
   1309 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
   1310 		if (success && resp != NULL)
   1311 			ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
   1312 			    sshbuf_len(resp));
   1313 		packet_send();
   1314 		packet_write_wait();
   1315 	}
   1316 	free(rtype);
   1317 	sshbuf_free(resp);
   1318 	return 0;
   1319 }
   1320 
   1321 static int
   1322 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
   1323 {
   1324 	Channel *c;
   1325 	int id, reply, success = 0;
   1326 	char *rtype;
   1327 
   1328 	id = packet_get_int();
   1329 	rtype = packet_get_string(NULL);
   1330 	reply = packet_get_char();
   1331 
   1332 	debug("server_input_channel_req: channel %d request %s reply %d",
   1333 	    id, rtype, reply);
   1334 
   1335 	if ((c = channel_lookup(id)) == NULL)
   1336 		packet_disconnect("server_input_channel_req: "
   1337 		    "unknown channel %d", id);
   1338 	if (!strcmp(rtype, "eow (at) openssh.com")) {
   1339 		packet_check_eom();
   1340 		chan_rcvd_eow(c);
   1341 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
   1342 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
   1343 		success = session_input_channel_req(c, rtype);
   1344 	if (reply && !(c->flags & CHAN_CLOSE_SENT)) {
   1345 		packet_start(success ?
   1346 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
   1347 		packet_put_int(c->remote_id);
   1348 		packet_send();
   1349 	}
   1350 	free(rtype);
   1351 	return 0;
   1352 }
   1353 
   1354 static void
   1355 server_init_dispatch_20(void)
   1356 {
   1357 	debug("server_init_dispatch_20");
   1358 	dispatch_init(&dispatch_protocol_error);
   1359 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
   1360 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
   1361 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
   1362 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
   1363 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
   1364 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
   1365 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
   1366 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
   1367 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
   1368 	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
   1369 	/* client_alive */
   1370 	dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
   1371 	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
   1372 	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
   1373 	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
   1374 	/* rekeying */
   1375 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
   1376 }
   1377 static void
   1378 server_init_dispatch_13(void)
   1379 {
   1380 	debug("server_init_dispatch_13");
   1381 	dispatch_init(NULL);
   1382 	dispatch_set(SSH_CMSG_EOF, &server_input_eof);
   1383 	dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
   1384 	dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
   1385 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
   1386 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
   1387 	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
   1388 	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
   1389 	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
   1390 	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
   1391 }
   1392 static void
   1393 server_init_dispatch_15(void)
   1394 {
   1395 	server_init_dispatch_13();
   1396 	debug("server_init_dispatch_15");
   1397 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
   1398 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
   1399 }
   1400 static void
   1401 server_init_dispatch(void)
   1402 {
   1403 	if (compat20)
   1404 		server_init_dispatch_20();
   1405 	else if (compat13)
   1406 		server_init_dispatch_13();
   1407 	else
   1408 		server_init_dispatch_15();
   1409 }
   1410