xref: /netbsd-src/crypto/external/bsd/openssh/dist/serverloop.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*	$NetBSD: serverloop.c,v 1.12 2015/04/13 18:00:47 christos Exp $	*/
2 /* $OpenBSD: serverloop.c,v 1.178 2015/02/20 22:17:21 djm Exp $ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * 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.12 2015/04/13 18:00:47 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@openssh.com");
275 		packet_put_char(1);	/* boolean: want reply */
276 	} else {
277 		channel_request_start(channel_id, "keepalive@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 				int r;
865 				debug("need rekeying");
866 				if (active_state->kex)
867 					active_state->kex->done = 0;
868 				if ((r = kex_send_kexinit(active_state)) != 0)
869 					logit("%s: kex_send_kexinit: %s",
870 					    __func__, ssh_err(r));
871 			}
872 		}
873 		process_input(readset);
874 		if (connection_closed)
875 			break;
876 		process_output(writeset);
877 	}
878 	collect_children();
879 
880 	free(readset);
881 	free(writeset);
882 
883 	/* free all channels, no more reads and writes */
884 	channel_free_all();
885 
886 	/* free remaining sessions, e.g. remove wtmp entries */
887 	session_destroy_all(NULL);
888 	total_time = get_current_time() - start_time;
889 	logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
890 	      get_remote_ipaddr(), get_remote_port(),
891 	      stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time,
892 	      fdout_bytes / total_time);
893 }
894 
895 static int
896 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
897 {
898 	debug("Got %d/%u for keepalive", type, seq);
899 	/*
900 	 * reset timeout, since we got a sane answer from the client.
901 	 * even if this was generated by something other than
902 	 * the bogus CHANNEL_REQUEST we send for keepalives.
903 	 */
904 	packet_set_alive_timeouts(0);
905 	return 0;
906 }
907 
908 static int
909 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
910 {
911 	char *data;
912 	u_int data_len;
913 
914 	/* Stdin data from the client.  Append it to the buffer. */
915 	/* Ignore any data if the client has closed stdin. */
916 	if (fdin == -1)
917 		return 0;
918 	data = packet_get_string(&data_len);
919 	packet_check_eom();
920 	buffer_append(&stdin_buffer, data, data_len);
921 	explicit_bzero(data, data_len);
922 	free(data);
923 	return 0;
924 }
925 
926 static int
927 server_input_eof(int type, u_int32_t seq, void *ctxt)
928 {
929 	/*
930 	 * Eof from the client.  The stdin descriptor to the
931 	 * program will be closed when all buffered data has
932 	 * drained.
933 	 */
934 	debug("EOF received for stdin.");
935 	packet_check_eom();
936 	stdin_eof = 1;
937 	return 0;
938 }
939 
940 static int
941 server_input_window_size(int type, u_int32_t seq, void *ctxt)
942 {
943 	u_int row = packet_get_int();
944 	u_int col = packet_get_int();
945 	u_int xpixel = packet_get_int();
946 	u_int ypixel = packet_get_int();
947 
948 	debug("Window change received.");
949 	packet_check_eom();
950 	if (fdin != -1)
951 		pty_change_window_size(fdin, row, col, xpixel, ypixel);
952 	return 0;
953 }
954 
955 static Channel *
956 server_request_direct_tcpip(void)
957 {
958 	Channel *c = NULL;
959 	char *target, *originator;
960 	u_short target_port, originator_port;
961 
962 	target = packet_get_string(NULL);
963 	target_port = packet_get_int();
964 	originator = packet_get_string(NULL);
965 	originator_port = packet_get_int();
966 	packet_check_eom();
967 
968 	debug("server_request_direct_tcpip: originator %s port %d, target %s "
969 	    "port %d", originator, originator_port, target, target_port);
970 
971 	/* XXX fine grained permissions */
972 	if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
973 	    !no_port_forwarding_flag) {
974 		c = channel_connect_to_port(target, target_port,
975 		    "direct-tcpip", "direct-tcpip");
976 	} else {
977 		logit("refused local port forward: "
978 		    "originator %s port %d, target %s port %d",
979 		    originator, originator_port, target, target_port);
980 	}
981 
982 	free(originator);
983 	free(target);
984 
985 	return c;
986 }
987 
988 static Channel *
989 server_request_direct_streamlocal(void)
990 {
991 	Channel *c = NULL;
992 	char *target, *originator;
993 	u_short originator_port;
994 
995 	target = packet_get_string(NULL);
996 	originator = packet_get_string(NULL);
997 	originator_port = packet_get_int();
998 	packet_check_eom();
999 
1000 	debug("server_request_direct_streamlocal: originator %s port %d, target %s",
1001 	    originator, originator_port, target);
1002 
1003 	/* XXX fine grained permissions */
1004 	if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
1005 	    !no_port_forwarding_flag) {
1006 		c = channel_connect_to_path(target,
1007 		    "direct-streamlocal@openssh.com", "direct-streamlocal");
1008 	} else {
1009 		logit("refused streamlocal port forward: "
1010 		    "originator %s port %d, target %s",
1011 		    originator, originator_port, target);
1012 	}
1013 
1014 	free(originator);
1015 	free(target);
1016 
1017 	return c;
1018 }
1019 
1020 static Channel *
1021 server_request_tun(void)
1022 {
1023 	Channel *c = NULL;
1024 	int mode, tun;
1025 	int sock;
1026 
1027 	mode = packet_get_int();
1028 	switch (mode) {
1029 	case SSH_TUNMODE_POINTOPOINT:
1030 	case SSH_TUNMODE_ETHERNET:
1031 		break;
1032 	default:
1033 		packet_send_debug("Unsupported tunnel device mode.");
1034 		return NULL;
1035 	}
1036 	if ((options.permit_tun & mode) == 0) {
1037 		packet_send_debug("Server has rejected tunnel device "
1038 		    "forwarding");
1039 		return NULL;
1040 	}
1041 
1042 	tun = packet_get_int();
1043 	if (forced_tun_device != -1) {
1044 		if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
1045 			goto done;
1046 		tun = forced_tun_device;
1047 	}
1048 	sock = tun_open(tun, mode);
1049 	if (sock < 0)
1050 		goto done;
1051 	if (options.hpn_disabled)
1052 	c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1053 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1054 	else
1055 		c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1056 		    options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1057 	c->datagram = 1;
1058 
1059  done:
1060 	if (c == NULL)
1061 		packet_send_debug("Failed to open the tunnel device.");
1062 	return c;
1063 }
1064 
1065 static Channel *
1066 server_request_session(void)
1067 {
1068 	Channel *c;
1069 
1070 	debug("input_session_request");
1071 	packet_check_eom();
1072 
1073 	if (no_more_sessions) {
1074 		packet_disconnect("Possible attack: attempt to open a session "
1075 		    "after additional sessions disabled");
1076 	}
1077 
1078 	/*
1079 	 * A server session has no fd to read or write until a
1080 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
1081 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
1082 	 * CHANNEL_REQUEST messages is registered.
1083 	 */
1084 	c = channel_new("session", SSH_CHANNEL_LARVAL,
1085 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1086 	    0, "server-session", 1);
1087 	if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled))
1088 		c->dynamic_window = 1;
1089 	if (session_open(the_authctxt, c->self) != 1) {
1090 		debug("session open failed, free channel %d", c->self);
1091 		channel_free(c);
1092 		return NULL;
1093 	}
1094 	channel_register_cleanup(c->self, session_close_by_channel, 0);
1095 	return c;
1096 }
1097 
1098 static int
1099 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1100 {
1101 	Channel *c = NULL;
1102 	char *ctype;
1103 	int rchan;
1104 	u_int rmaxpack, rwindow, len;
1105 
1106 	ctype = packet_get_string(&len);
1107 	rchan = packet_get_int();
1108 	rwindow = packet_get_int();
1109 	rmaxpack = packet_get_int();
1110 
1111 	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1112 	    ctype, rchan, rwindow, rmaxpack);
1113 
1114 	if (strcmp(ctype, "session") == 0) {
1115 		c = server_request_session();
1116 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
1117 		c = server_request_direct_tcpip();
1118 	} else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
1119 		c = server_request_direct_streamlocal();
1120 	} else if (strcmp(ctype, "tun@openssh.com") == 0) {
1121 		c = server_request_tun();
1122 	}
1123 	if (c != NULL) {
1124 		debug("server_input_channel_open: confirm %s", ctype);
1125 		c->remote_id = rchan;
1126 		c->remote_window = rwindow;
1127 		c->remote_maxpacket = rmaxpack;
1128 		if (c->type != SSH_CHANNEL_CONNECTING) {
1129 			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1130 			packet_put_int(c->remote_id);
1131 			packet_put_int(c->self);
1132 			packet_put_int(c->local_window);
1133 			packet_put_int(c->local_maxpacket);
1134 			packet_send();
1135 		}
1136 	} else {
1137 		debug("server_input_channel_open: failure %s", ctype);
1138 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1139 		packet_put_int(rchan);
1140 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1141 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1142 			packet_put_cstring("open failed");
1143 			packet_put_cstring("");
1144 		}
1145 		packet_send();
1146 	}
1147 	free(ctype);
1148 	return 0;
1149 }
1150 
1151 static int
1152 server_input_hostkeys_prove(struct sshbuf **respp)
1153 {
1154 	struct ssh *ssh = active_state; /* XXX */
1155 	struct sshbuf *resp = NULL;
1156 	struct sshbuf *sigbuf = NULL;
1157 	struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
1158 	int r, ndx, success = 0;
1159 	const u_char *blob;
1160 	u_char *sig = 0;
1161 	size_t blen, slen;
1162 
1163 	if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
1164 		fatal("%s: sshbuf_new", __func__);
1165 
1166 	while (ssh_packet_remaining(ssh) > 0) {
1167 		sshkey_free(key);
1168 		key = NULL;
1169 		if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
1170 		    (r = sshkey_from_blob(blob, blen, &key)) != 0) {
1171 			error("%s: couldn't parse key: %s",
1172 			    __func__, ssh_err(r));
1173 			goto out;
1174 		}
1175 		/*
1176 		 * Better check that this is actually one of our hostkeys
1177 		 * before attempting to sign anything with it.
1178 		 */
1179 		if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
1180 			error("%s: unknown host %s key",
1181 			    __func__, sshkey_type(key));
1182 			goto out;
1183 		}
1184 		/*
1185 		 * XXX refactor: make kex->sign just use an index rather
1186 		 * than passing in public and private keys
1187 		 */
1188 		if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
1189 		    (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
1190 			error("%s: can't retrieve hostkey %d", __func__, ndx);
1191 			goto out;
1192 		}
1193 		sshbuf_reset(sigbuf);
1194 		free(sig);
1195 		sig = NULL;
1196 		if ((r = sshbuf_put_cstring(sigbuf,
1197 		    "hostkeys-prove-00@openssh.com")) != 0 ||
1198 		    (r = sshbuf_put_string(sigbuf,
1199 		    ssh->kex->session_id, ssh->kex->session_id_len)) != 0 ||
1200 		    (r = sshkey_puts(key, sigbuf)) != 0 ||
1201 		    (r = ssh->kex->sign(key_prv, key_pub, &sig, &slen,
1202 		    sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), 0)) != 0 ||
1203 		    (r = sshbuf_put_string(resp, sig, slen)) != 0) {
1204 			error("%s: couldn't prepare signature: %s",
1205 			    __func__, ssh_err(r));
1206 			goto out;
1207 		}
1208 	}
1209 	/* Success */
1210 	*respp = resp;
1211 	resp = NULL; /* don't free it */
1212 	success = 1;
1213  out:
1214 	free(sig);
1215 	sshbuf_free(resp);
1216 	sshbuf_free(sigbuf);
1217 	sshkey_free(key);
1218 	return success;
1219 }
1220 
1221 static int
1222 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1223 {
1224 	char *rtype;
1225 	int want_reply;
1226 	int r, success = 0, allocated_listen_port = 0;
1227 	struct sshbuf *resp = NULL;
1228 
1229 	rtype = packet_get_string(NULL);
1230 	want_reply = packet_get_char();
1231 	debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1232 
1233 	/* -R style forwarding */
1234 	if (strcmp(rtype, "tcpip-forward") == 0) {
1235 		struct passwd *pw;
1236 		struct Forward fwd;
1237 
1238 		pw = the_authctxt->pw;
1239 		if (pw == NULL || !the_authctxt->valid)
1240 			fatal("server_input_global_request: no/invalid user");
1241 		memset(&fwd, 0, sizeof(fwd));
1242 		fwd.listen_host = packet_get_string(NULL);
1243 		fwd.listen_port = (u_short)packet_get_int();
1244 		debug("server_input_global_request: tcpip-forward listen %s port %d",
1245 		    fwd.listen_host, fwd.listen_port);
1246 
1247 		/* check permissions */
1248 		if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
1249 		    no_port_forwarding_flag ||
1250 		    (!want_reply && fwd.listen_port == 0) ||
1251 		    (fwd.listen_port != 0 && fwd.listen_port < IPPORT_RESERVED &&
1252 		    pw->pw_uid != 0)) {
1253 			success = 0;
1254 			packet_send_debug("Server has disabled port forwarding.");
1255 		} else {
1256 			/* Start listening on the port */
1257 			success = channel_setup_remote_fwd_listener(&fwd,
1258 			    &allocated_listen_port, &options.fwd_opts);
1259 		}
1260 		free(fwd.listen_host);
1261 		if ((resp = sshbuf_new()) == NULL)
1262 			fatal("%s: sshbuf_new", __func__);
1263 		if ((r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
1264 			fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
1265 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1266 		struct Forward fwd;
1267 
1268 		memset(&fwd, 0, sizeof(fwd));
1269 		fwd.listen_host = packet_get_string(NULL);
1270 		fwd.listen_port = (u_short)packet_get_int();
1271 		debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1272 		    fwd.listen_host, fwd.listen_port);
1273 
1274 		success = channel_cancel_rport_listener(&fwd);
1275 		free(fwd.listen_host);
1276 	} else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
1277 		struct Forward fwd;
1278 
1279 		memset(&fwd, 0, sizeof(fwd));
1280 		fwd.listen_path = packet_get_string(NULL);
1281 		debug("server_input_global_request: streamlocal-forward listen path %s",
1282 		    fwd.listen_path);
1283 
1284 		/* check permissions */
1285 		if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
1286 		    || no_port_forwarding_flag) {
1287 			success = 0;
1288 			packet_send_debug("Server has disabled port forwarding.");
1289 		} else {
1290 			/* Start listening on the socket */
1291 			success = channel_setup_remote_fwd_listener(
1292 			    &fwd, NULL, &options.fwd_opts);
1293 		}
1294 		free(fwd.listen_path);
1295 	} else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
1296 		struct Forward fwd;
1297 
1298 		memset(&fwd, 0, sizeof(fwd));
1299 		fwd.listen_path = packet_get_string(NULL);
1300 		debug("%s: cancel-streamlocal-forward path %s", __func__,
1301 		    fwd.listen_path);
1302 
1303 		success = channel_cancel_rport_listener(&fwd);
1304 		free(fwd.listen_path);
1305 	} else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
1306 		no_more_sessions = 1;
1307 		success = 1;
1308 	} else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
1309 		success = server_input_hostkeys_prove(&resp);
1310 	}
1311 	if (want_reply) {
1312 		packet_start(success ?
1313 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1314 		if (success && resp != NULL)
1315 			ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
1316 			    sshbuf_len(resp));
1317 		packet_send();
1318 		packet_write_wait();
1319 	}
1320 	free(rtype);
1321 	sshbuf_free(resp);
1322 	return 0;
1323 }
1324 
1325 static int
1326 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1327 {
1328 	Channel *c;
1329 	int id, reply, success = 0;
1330 	char *rtype;
1331 
1332 	id = packet_get_int();
1333 	rtype = packet_get_string(NULL);
1334 	reply = packet_get_char();
1335 
1336 	debug("server_input_channel_req: channel %d request %s reply %d",
1337 	    id, rtype, reply);
1338 
1339 	if ((c = channel_lookup(id)) == NULL)
1340 		packet_disconnect("server_input_channel_req: "
1341 		    "unknown channel %d", id);
1342 	if (!strcmp(rtype, "eow@openssh.com")) {
1343 		packet_check_eom();
1344 		chan_rcvd_eow(c);
1345 	} else if ((c->type == SSH_CHANNEL_LARVAL ||
1346 	    c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
1347 		success = session_input_channel_req(c, rtype);
1348 	if (reply && !(c->flags & CHAN_CLOSE_SENT)) {
1349 		packet_start(success ?
1350 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1351 		packet_put_int(c->remote_id);
1352 		packet_send();
1353 	}
1354 	free(rtype);
1355 	return 0;
1356 }
1357 
1358 static void
1359 server_init_dispatch_20(void)
1360 {
1361 	debug("server_init_dispatch_20");
1362 	dispatch_init(&dispatch_protocol_error);
1363 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1364 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1365 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1366 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1367 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1368 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1369 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1370 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1371 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1372 	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1373 	/* client_alive */
1374 	dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
1375 	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1376 	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1377 	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1378 	/* rekeying */
1379 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1380 }
1381 static void
1382 server_init_dispatch_13(void)
1383 {
1384 	debug("server_init_dispatch_13");
1385 	dispatch_init(NULL);
1386 	dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1387 	dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1388 	dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1389 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1390 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1391 	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1392 	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1393 	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1394 	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1395 }
1396 static void
1397 server_init_dispatch_15(void)
1398 {
1399 	server_init_dispatch_13();
1400 	debug("server_init_dispatch_15");
1401 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1402 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1403 }
1404 static void
1405 server_init_dispatch(void)
1406 {
1407 	if (compat20)
1408 		server_init_dispatch_20();
1409 	else if (compat13)
1410 		server_init_dispatch_13();
1411 	else
1412 		server_init_dispatch_15();
1413 }
1414