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