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