drm - Fix deadlock in ttm pager
[dragonfly.git] / crypto / openssh / serverloop.c
1 /* $OpenBSD: serverloop.c,v 1.162 2012/06/20 04:42:58 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/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 "servconf.h"
65 #include "canohost.h"
66 #include "sshpty.h"
67 #include "channels.h"
68 #include "compat.h"
69 #include "ssh1.h"
70 #include "ssh2.h"
71 #include "key.h"
72 #include "cipher.h"
73 #include "kex.h"
74 #include "hostfile.h"
75 #include "auth.h"
76 #include "session.h"
77 #include "dispatch.h"
78 #include "auth-options.h"
79 #include "serverloop.h"
80 #include "misc.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                 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_int 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 = options.client_alive_interval * 1000;
322         }
323
324         if (compat20) {
325 #if 0
326                 /* wrong: bad condition XXX */
327                 if (channel_not_very_much_buffered_data())
328 #endif
329                 FD_SET(connection_in, *readsetp);
330         } else {
331                 /*
332                  * Read packets from the client unless we have too much
333                  * buffered stdin or channel data.
334                  */
335                 if (buffer_len(&stdin_buffer) < buffer_high &&
336                     channel_not_very_much_buffered_data())
337                         FD_SET(connection_in, *readsetp);
338                 /*
339                  * If there is not too much data already buffered going to
340                  * the client, try to get some more data from the program.
341                  */
342                 if (packet_not_very_much_data_to_write()) {
343                         program_alive_scheduled = child_terminated;
344                         if (!fdout_eof)
345                                 FD_SET(fdout, *readsetp);
346                         if (!fderr_eof)
347                                 FD_SET(fderr, *readsetp);
348                 }
349                 /*
350                  * If we have buffered data, try to write some of that data
351                  * to the program.
352                  */
353                 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
354                         FD_SET(fdin, *writesetp);
355         }
356         notify_prepare(*readsetp);
357
358         /*
359          * If we have buffered packet data going to the client, mark that
360          * descriptor.
361          */
362         if (packet_have_data_to_write())
363                 FD_SET(connection_out, *writesetp);
364
365         /*
366          * If child has terminated and there is enough buffer space to read
367          * from it, then read as much as is available and exit.
368          */
369         if (child_terminated && packet_not_very_much_data_to_write())
370                 if (max_time_milliseconds == 0 || client_alive_scheduled)
371                         max_time_milliseconds = 100;
372
373         if (max_time_milliseconds == 0)
374                 tvp = NULL;
375         else {
376                 tv.tv_sec = max_time_milliseconds / 1000;
377                 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
378                 tvp = &tv;
379         }
380
381         /* Wait for something to happen, or the timeout to expire. */
382         ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
383
384         if (ret == -1) {
385                 memset(*readsetp, 0, *nallocp);
386                 memset(*writesetp, 0, *nallocp);
387                 if (errno != EINTR)
388                         error("select: %.100s", strerror(errno));
389         } else {
390                 if (ret == 0 && client_alive_scheduled)
391                         client_alive_check();
392                 if (!compat20 && program_alive_scheduled && fdin_is_tty) {
393                         if (!fdout_eof)
394                                 FD_SET(fdout, *readsetp);
395                         if (!fderr_eof)
396                                 FD_SET(fderr, *readsetp);
397                 }
398         }
399
400         notify_done(*readsetp);
401 }
402
403 /*
404  * Processes input from the client and the program.  Input data is stored
405  * in buffers and processed later.
406  */
407 static void
408 process_input(fd_set *readset)
409 {
410         int len;
411         char buf[16384];
412
413         /* Read and buffer any input data from the client. */
414         if (FD_ISSET(connection_in, readset)) {
415                 int cont = 0;
416                 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
417                 if (len == 0) {
418                         if (cont)
419                                 return;
420                         verbose("Connection closed by %.100s",
421                             get_remote_ipaddr());
422                         connection_closed = 1;
423                         if (compat20)
424                                 return;
425                         cleanup_exit(255);
426                 } else if (len < 0) {
427                         if (errno != EINTR && errno != EAGAIN &&
428                             errno != EWOULDBLOCK) {
429                                 verbose("Read error from remote host "
430                                     "%.100s: %.100s",
431                                     get_remote_ipaddr(), strerror(errno));
432                                 cleanup_exit(255);
433                         }
434                 } else {
435                         /* Buffer any received data. */
436                         packet_process_incoming(buf, len);
437                         fdout_bytes += len;
438                 }
439         }
440         if (compat20)
441                 return;
442
443         /* Read and buffer any available stdout data from the program. */
444         if (!fdout_eof && FD_ISSET(fdout, readset)) {
445                 errno = 0;
446                 len = read(fdout, buf, sizeof(buf));
447                 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
448                     errno == EWOULDBLOCK) && !child_terminated))) {
449                         /* do nothing */
450 #ifndef PTY_ZEROREAD
451                 } else if (len <= 0) {
452 #else
453                 } else if ((!isatty(fdout) && len <= 0) ||
454                     (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
455 #endif
456                         fdout_eof = 1;
457                 } else {
458                         buffer_append(&stdout_buffer, buf, len);
459                         fdout_bytes += len;
460                         debug ("FD out now: %ld", fdout_bytes);
461                 }
462         }
463         /* Read and buffer any available stderr data from the program. */
464         if (!fderr_eof && FD_ISSET(fderr, readset)) {
465                 errno = 0;
466                 len = read(fderr, buf, sizeof(buf));
467                 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
468                     errno == EWOULDBLOCK) && !child_terminated))) {
469                         /* do nothing */
470 #ifndef PTY_ZEROREAD
471                 } else if (len <= 0) {
472 #else
473                 } else if ((!isatty(fderr) && len <= 0) ||
474                     (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
475 #endif
476                         fderr_eof = 1;
477                 } else {
478                         buffer_append(&stderr_buffer, buf, len);
479                 }
480         }
481 }
482
483 /*
484  * Sends data from internal buffers to client program stdin.
485  */
486 static void
487 process_output(fd_set *writeset)
488 {
489         struct termios tio;
490         u_char *data;
491         u_int dlen;
492         int len;
493
494         /* Write buffered data to program stdin. */
495         if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
496                 data = buffer_ptr(&stdin_buffer);
497                 dlen = buffer_len(&stdin_buffer);
498                 len = write(fdin, data, dlen);
499                 if (len < 0 &&
500                     (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
501                         /* do nothing */
502                 } else if (len <= 0) {
503                         if (fdin != fdout)
504                                 close(fdin);
505                         else
506                                 shutdown(fdin, SHUT_WR); /* We will no longer send. */
507                         fdin = -1;
508                 } else {
509                         /* Successful write. */
510                         if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
511                             tcgetattr(fdin, &tio) == 0 &&
512                             !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
513                                 /*
514                                  * Simulate echo to reduce the impact of
515                                  * traffic analysis
516                                  */
517                                 packet_send_ignore(len);
518                                 packet_send();
519                         }
520                         /* Consume the data from the buffer. */
521                         buffer_consume(&stdin_buffer, len);
522                         /* Update the count of bytes written to the program. */
523                         stdin_bytes += len;
524                 }
525         }
526         /* Send any buffered packet data to the client. */
527         if (FD_ISSET(connection_out, writeset))
528                 stdin_bytes += packet_write_poll();
529 }
530
531 /*
532  * Wait until all buffered output has been sent to the client.
533  * This is used when the program terminates.
534  */
535 static void
536 drain_output(void)
537 {
538         /* Send any buffered stdout data to the client. */
539         if (buffer_len(&stdout_buffer) > 0) {
540                 packet_start(SSH_SMSG_STDOUT_DATA);
541                 packet_put_string(buffer_ptr(&stdout_buffer),
542                                   buffer_len(&stdout_buffer));
543                 packet_send();
544                 /* Update the count of sent bytes. */
545                 stdout_bytes += buffer_len(&stdout_buffer);
546         }
547         /* Send any buffered stderr data to the client. */
548         if (buffer_len(&stderr_buffer) > 0) {
549                 packet_start(SSH_SMSG_STDERR_DATA);
550                 packet_put_string(buffer_ptr(&stderr_buffer),
551                                   buffer_len(&stderr_buffer));
552                 packet_send();
553                 /* Update the count of sent bytes. */
554                 stderr_bytes += buffer_len(&stderr_buffer);
555         }
556         /* Wait until all buffered data has been written to the client. */
557         packet_write_wait();
558 }
559
560 static void
561 process_buffered_input_packets(void)
562 {
563         dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
564 }
565
566 /*
567  * Performs the interactive session.  This handles data transmission between
568  * the client and the program.  Note that the notion of stdin, stdout, and
569  * stderr in this function is sort of reversed: this function writes to
570  * stdin (of the child program), and reads from stdout and stderr (of the
571  * child program).
572  */
573 void
574 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
575 {
576         fd_set *readset = NULL, *writeset = NULL;
577         int max_fd = 0;
578         u_int nalloc = 0;
579         int wait_status;        /* Status returned by wait(). */
580         pid_t wait_pid;         /* pid returned by wait(). */
581         int waiting_termination = 0;    /* Have displayed waiting close message. */
582         u_int max_time_milliseconds;
583         u_int previous_stdout_buffer_bytes;
584         u_int stdout_buffer_bytes;
585         int type;
586
587         debug("Entering interactive session.");
588
589         /* Initialize the SIGCHLD kludge. */
590         child_terminated = 0;
591         mysignal(SIGCHLD, sigchld_handler);
592
593         if (!use_privsep) {
594                 signal(SIGTERM, sigterm_handler);
595                 signal(SIGINT, sigterm_handler);
596                 signal(SIGQUIT, sigterm_handler);
597         }
598
599         /* Initialize our global variables. */
600         fdin = fdin_arg;
601         fdout = fdout_arg;
602         fderr = fderr_arg;
603
604         /* nonblocking IO */
605         set_nonblock(fdin);
606         set_nonblock(fdout);
607         /* we don't have stderr for interactive terminal sessions, see below */
608         if (fderr != -1)
609                 set_nonblock(fderr);
610
611         if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
612                 fdin_is_tty = 1;
613
614         connection_in = packet_get_connection_in();
615         connection_out = packet_get_connection_out();
616
617         notify_setup();
618
619         previous_stdout_buffer_bytes = 0;
620
621         /* Set approximate I/O buffer size. */
622         if (packet_is_interactive())
623                 buffer_high = 4096;
624         else
625                 buffer_high = 64 * 1024;
626
627 #if 0
628         /* Initialize max_fd to the maximum of the known file descriptors. */
629         max_fd = MAX(connection_in, connection_out);
630         max_fd = MAX(max_fd, fdin);
631         max_fd = MAX(max_fd, fdout);
632         if (fderr != -1)
633                 max_fd = MAX(max_fd, fderr);
634 #endif
635
636         /* Initialize Initialize buffers. */
637         buffer_init(&stdin_buffer);
638         buffer_init(&stdout_buffer);
639         buffer_init(&stderr_buffer);
640
641         /*
642          * If we have no separate fderr (which is the case when we have a pty
643          * - there we cannot make difference between data sent to stdout and
644          * stderr), indicate that we have seen an EOF from stderr.  This way
645          * we don't need to check the descriptor everywhere.
646          */
647         if (fderr == -1)
648                 fderr_eof = 1;
649
650         server_init_dispatch();
651
652         /* Main loop of the server for the interactive session mode. */
653         for (;;) {
654
655                 /* Process buffered packets from the client. */
656                 process_buffered_input_packets();
657
658                 /*
659                  * If we have received eof, and there is no more pending
660                  * input data, cause a real eof by closing fdin.
661                  */
662                 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
663                         if (fdin != fdout)
664                                 close(fdin);
665                         else
666                                 shutdown(fdin, SHUT_WR); /* We will no longer send. */
667                         fdin = -1;
668                 }
669                 /* Make packets from buffered stderr data to send to the client. */
670                 make_packets_from_stderr_data();
671
672                 /*
673                  * Make packets from buffered stdout data to send to the
674                  * client. If there is very little to send, this arranges to
675                  * not send them now, but to wait a short while to see if we
676                  * are getting more data. This is necessary, as some systems
677                  * wake up readers from a pty after each separate character.
678                  */
679                 max_time_milliseconds = 0;
680                 stdout_buffer_bytes = buffer_len(&stdout_buffer);
681                 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
682                     stdout_buffer_bytes != previous_stdout_buffer_bytes) {
683                         /* try again after a while */
684                         max_time_milliseconds = 10;
685                 } else {
686                         /* Send it now. */
687                         make_packets_from_stdout_data();
688                 }
689                 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
690
691                 /* Send channel data to the client. */
692                 if (packet_not_very_much_data_to_write())
693                         channel_output_poll();
694
695                 /*
696                  * Bail out of the loop if the program has closed its output
697                  * descriptors, and we have no more data to send to the
698                  * client, and there is no pending buffered data.
699                  */
700                 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
701                     buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
702                         if (!channel_still_open())
703                                 break;
704                         if (!waiting_termination) {
705                                 const char *s = "Waiting for forwarded connections to terminate...\r\n";
706                                 char *cp;
707                                 waiting_termination = 1;
708                                 buffer_append(&stderr_buffer, s, strlen(s));
709
710                                 /* Display list of open channels. */
711                                 cp = channel_open_message();
712                                 buffer_append(&stderr_buffer, cp, strlen(cp));
713                                 xfree(cp);
714                         }
715                 }
716                 max_fd = MAX(connection_in, connection_out);
717                 max_fd = MAX(max_fd, fdin);
718                 max_fd = MAX(max_fd, fdout);
719                 max_fd = MAX(max_fd, fderr);
720                 max_fd = MAX(max_fd, notify_pipe[0]);
721
722                 /* Sleep in select() until we can do something. */
723                 wait_until_can_do_something(&readset, &writeset, &max_fd,
724                     &nalloc, max_time_milliseconds);
725
726                 if (received_sigterm) {
727                         logit("Exiting on signal %d", received_sigterm);
728                         /* Clean up sessions, utmp, etc. */
729                         cleanup_exit(255);
730                 }
731
732                 /* Process any channel events. */
733                 channel_after_select(readset, writeset);
734
735                 /* Process input from the client and from program stdout/stderr. */
736                 process_input(readset);
737
738                 /* Process output to the client and to program stdin. */
739                 process_output(writeset);
740         }
741         if (readset)
742                 xfree(readset);
743         if (writeset)
744                 xfree(writeset);
745
746         /* Cleanup and termination code. */
747
748         /* Wait until all output has been sent to the client. */
749         drain_output();
750
751         debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
752             stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
753
754         /* Free and clear the buffers. */
755         buffer_free(&stdin_buffer);
756         buffer_free(&stdout_buffer);
757         buffer_free(&stderr_buffer);
758
759         /* Close the file descriptors. */
760         if (fdout != -1)
761                 close(fdout);
762         fdout = -1;
763         fdout_eof = 1;
764         if (fderr != -1)
765                 close(fderr);
766         fderr = -1;
767         fderr_eof = 1;
768         if (fdin != -1)
769                 close(fdin);
770         fdin = -1;
771
772         channel_free_all();
773
774         /* We no longer want our SIGCHLD handler to be called. */
775         mysignal(SIGCHLD, SIG_DFL);
776
777         while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
778                 if (errno != EINTR)
779                         packet_disconnect("wait: %.100s", strerror(errno));
780         if (wait_pid != pid)
781                 error("Strange, wait returned pid %ld, expected %ld",
782                     (long)wait_pid, (long)pid);
783
784         /* Check if it exited normally. */
785         if (WIFEXITED(wait_status)) {
786                 /* Yes, normal exit.  Get exit status and send it to the client. */
787                 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
788                 packet_start(SSH_SMSG_EXITSTATUS);
789                 packet_put_int(WEXITSTATUS(wait_status));
790                 packet_send();
791                 packet_write_wait();
792
793                 /*
794                  * Wait for exit confirmation.  Note that there might be
795                  * other packets coming before it; however, the program has
796                  * already died so we just ignore them.  The client is
797                  * supposed to respond with the confirmation when it receives
798                  * the exit status.
799                  */
800                 do {
801                         type = packet_read();
802                 }
803                 while (type != SSH_CMSG_EXIT_CONFIRMATION);
804
805                 debug("Received exit confirmation.");
806                 return;
807         }
808         /* Check if the program terminated due to a signal. */
809         if (WIFSIGNALED(wait_status))
810                 packet_disconnect("Command terminated on signal %d.",
811                                   WTERMSIG(wait_status));
812
813         /* Some weird exit cause.  Just exit. */
814         packet_disconnect("wait returned status %04x.", wait_status);
815         /* NOTREACHED */
816 }
817
818 static void
819 collect_children(void)
820 {
821         pid_t pid;
822         sigset_t oset, nset;
823         int status;
824
825         /* block SIGCHLD while we check for dead children */
826         sigemptyset(&nset);
827         sigaddset(&nset, SIGCHLD);
828         sigprocmask(SIG_BLOCK, &nset, &oset);
829         if (child_terminated) {
830                 debug("Received SIGCHLD.");
831                 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
832                     (pid < 0 && errno == EINTR))
833                         if (pid > 0)
834                                 session_close_by_pid(pid, status);
835                 child_terminated = 0;
836         }
837         sigprocmask(SIG_SETMASK, &oset, NULL);
838 }
839
840 void
841 server_loop2(Authctxt *authctxt)
842 {
843         fd_set *readset = NULL, *writeset = NULL;
844         int rekeying = 0, max_fd, nalloc = 0;
845         double start_time, total_time;
846
847         debug("Entering interactive session for SSH2.");
848         start_time = get_current_time();
849
850         mysignal(SIGCHLD, sigchld_handler);
851         child_terminated = 0;
852         connection_in = packet_get_connection_in();
853         connection_out = packet_get_connection_out();
854
855         if (!use_privsep) {
856                 signal(SIGTERM, sigterm_handler);
857                 signal(SIGINT, sigterm_handler);
858                 signal(SIGQUIT, sigterm_handler);
859         }
860
861         notify_setup();
862
863         max_fd = MAX(connection_in, connection_out);
864         max_fd = MAX(max_fd, notify_pipe[0]);
865
866         server_init_dispatch();
867
868         for (;;) {
869                 process_buffered_input_packets();
870
871                 rekeying = (xxx_kex != NULL && !xxx_kex->done);
872
873                 if (!rekeying && packet_not_very_much_data_to_write())
874                         channel_output_poll();
875                 wait_until_can_do_something(&readset, &writeset, &max_fd,
876                     &nalloc, 0);
877
878                 if (received_sigterm) {
879                         logit("Exiting on signal %d", received_sigterm);
880                         /* Clean up sessions, utmp, etc. */
881                         cleanup_exit(255);
882                 }
883
884                 collect_children();
885                 if (!rekeying) {
886                         channel_after_select(readset, writeset);
887                         if (packet_need_rekeying()) {
888                                 debug("need rekeying");
889                                 xxx_kex->done = 0;
890                                 kex_send_kexinit(xxx_kex);
891                         }
892                 }
893                 process_input(readset);
894                 if (connection_closed)
895                         break;
896                 process_output(writeset);
897         }
898         collect_children();
899
900         if (readset)
901                 xfree(readset);
902         if (writeset)
903                 xfree(writeset);
904
905         /* free all channels, no more reads and writes */
906         channel_free_all();
907
908         /* free remaining sessions, e.g. remove wtmp entries */
909         session_destroy_all(NULL);
910         total_time = get_current_time() - start_time;
911         logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
912               get_remote_ipaddr(), get_remote_port(),
913               stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time,
914               fdout_bytes / total_time);
915 }
916
917 static void
918 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
919 {
920         debug("Got %d/%u for keepalive", type, seq);
921         /*
922          * reset timeout, since we got a sane answer from the client.
923          * even if this was generated by something other than
924          * the bogus CHANNEL_REQUEST we send for keepalives.
925          */
926         packet_set_alive_timeouts(0);
927 }
928
929 static void
930 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
931 {
932         char *data;
933         u_int data_len;
934
935         /* Stdin data from the client.  Append it to the buffer. */
936         /* Ignore any data if the client has closed stdin. */
937         if (fdin == -1)
938                 return;
939         data = packet_get_string(&data_len);
940         packet_check_eom();
941         buffer_append(&stdin_buffer, data, data_len);
942         memset(data, 0, data_len);
943         xfree(data);
944 }
945
946 static void
947 server_input_eof(int type, u_int32_t seq, void *ctxt)
948 {
949         /*
950          * Eof from the client.  The stdin descriptor to the
951          * program will be closed when all buffered data has
952          * drained.
953          */
954         debug("EOF received for stdin.");
955         packet_check_eom();
956         stdin_eof = 1;
957 }
958
959 static void
960 server_input_window_size(int type, u_int32_t seq, void *ctxt)
961 {
962         u_int row = packet_get_int();
963         u_int col = packet_get_int();
964         u_int xpixel = packet_get_int();
965         u_int ypixel = packet_get_int();
966
967         debug("Window change received.");
968         packet_check_eom();
969         if (fdin != -1)
970                 pty_change_window_size(fdin, row, col, xpixel, ypixel);
971 }
972
973 static Channel *
974 server_request_direct_tcpip(void)
975 {
976         Channel *c;
977         char *target, *originator;
978         u_short target_port, originator_port;
979
980         target = packet_get_string(NULL);
981         target_port = packet_get_int();
982         originator = packet_get_string(NULL);
983         originator_port = packet_get_int();
984         packet_check_eom();
985
986         debug("server_request_direct_tcpip: originator %s port %d, target %s "
987             "port %d", originator, originator_port, target, target_port);
988
989         /* XXX check permission */
990         c = channel_connect_to(target, target_port,
991             "direct-tcpip", "direct-tcpip");
992
993         xfree(originator);
994         xfree(target);
995
996         return c;
997 }
998
999 static Channel *
1000 server_request_tun(void)
1001 {
1002         Channel *c = NULL;
1003         int mode, tun;
1004         int sock;
1005
1006         mode = packet_get_int();
1007         switch (mode) {
1008         case SSH_TUNMODE_POINTOPOINT:
1009         case SSH_TUNMODE_ETHERNET:
1010                 break;
1011         default:
1012                 packet_send_debug("Unsupported tunnel device mode.");
1013                 return NULL;
1014         }
1015         if ((options.permit_tun & mode) == 0) {
1016                 packet_send_debug("Server has rejected tunnel device "
1017                     "forwarding");
1018                 return NULL;
1019         }
1020
1021         tun = packet_get_int();
1022         if (forced_tun_device != -1) {
1023                 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
1024                         goto done;
1025                 tun = forced_tun_device;
1026         }
1027         sock = tun_open(tun, mode);
1028         if (sock < 0)
1029                 goto done;
1030         if (options.hpn_disabled)
1031         c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1032             CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1033         else
1034                 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1035                     options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1036         c->datagram = 1;
1037 #if defined(SSH_TUN_FILTER)
1038         if (mode == SSH_TUNMODE_POINTOPOINT)
1039                 channel_register_filter(c->self, sys_tun_infilter,
1040                     sys_tun_outfilter, NULL, NULL);
1041 #endif
1042
1043  done:
1044         if (c == NULL)
1045                 packet_send_debug("Failed to open the tunnel device.");
1046         return c;
1047 }
1048
1049 static Channel *
1050 server_request_session(void)
1051 {
1052         Channel *c;
1053
1054         debug("input_session_request");
1055         packet_check_eom();
1056
1057         if (no_more_sessions) {
1058                 packet_disconnect("Possible attack: attempt to open a session "
1059                     "after additional sessions disabled");
1060         }
1061
1062         /*
1063          * A server session has no fd to read or write until a
1064          * CHANNEL_REQUEST for a shell is made, so we set the type to
1065          * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
1066          * CHANNEL_REQUEST messages is registered.
1067          */
1068         c = channel_new("session", SSH_CHANNEL_LARVAL,
1069             -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1070             0, "server-session", 1);
1071         if ((options.tcp_rcv_buf_poll) && (!options.hpn_disabled))
1072                 c->dynamic_window = 1;
1073         if (session_open(the_authctxt, c->self) != 1) {
1074                 debug("session open failed, free channel %d", c->self);
1075                 channel_free(c);
1076                 return NULL;
1077         }
1078         channel_register_cleanup(c->self, session_close_by_channel, 0);
1079         return c;
1080 }
1081
1082 static void
1083 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1084 {
1085         Channel *c = NULL;
1086         char *ctype;
1087         int rchan;
1088         u_int rmaxpack, rwindow, len;
1089
1090         ctype = packet_get_string(&len);
1091         rchan = packet_get_int();
1092         rwindow = packet_get_int();
1093         rmaxpack = packet_get_int();
1094
1095         debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1096             ctype, rchan, rwindow, rmaxpack);
1097
1098         if (strcmp(ctype, "session") == 0) {
1099                 c = server_request_session();
1100         } else if (strcmp(ctype, "direct-tcpip") == 0) {
1101                 c = server_request_direct_tcpip();
1102         } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1103                 c = server_request_tun();
1104         }
1105         if (c != NULL) {
1106                 debug("server_input_channel_open: confirm %s", ctype);
1107                 c->remote_id = rchan;
1108                 c->remote_window = rwindow;
1109                 c->remote_maxpacket = rmaxpack;
1110                 if (c->type != SSH_CHANNEL_CONNECTING) {
1111                         packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1112                         packet_put_int(c->remote_id);
1113                         packet_put_int(c->self);
1114                         packet_put_int(c->local_window);
1115                         packet_put_int(c->local_maxpacket);
1116                         packet_send();
1117                 }
1118         } else {
1119                 debug("server_input_channel_open: failure %s", ctype);
1120                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1121                 packet_put_int(rchan);
1122                 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1123                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1124                         packet_put_cstring("open failed");
1125                         packet_put_cstring("");
1126                 }
1127                 packet_send();
1128         }
1129         xfree(ctype);
1130 }
1131
1132 static void
1133 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1134 {
1135         char *rtype;
1136         int want_reply;
1137         int success = 0, allocated_listen_port = 0;
1138
1139         rtype = packet_get_string(NULL);
1140         want_reply = packet_get_char();
1141         debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1142
1143         /* -R style forwarding */
1144         if (strcmp(rtype, "tcpip-forward") == 0) {
1145                 struct passwd *pw;
1146                 char *listen_address;
1147                 u_short listen_port;
1148
1149                 pw = the_authctxt->pw;
1150                 if (pw == NULL || !the_authctxt->valid)
1151                         fatal("server_input_global_request: no/invalid user");
1152                 listen_address = packet_get_string(NULL);
1153                 listen_port = (u_short)packet_get_int();
1154                 debug("server_input_global_request: tcpip-forward listen %s port %d",
1155                     listen_address, listen_port);
1156
1157                 /* check permissions */
1158                 if (!options.allow_tcp_forwarding ||
1159                     no_port_forwarding_flag ||
1160                     (!want_reply && listen_port == 0)
1161 #ifndef NO_IPPORT_RESERVED_CONCEPT
1162                     || (listen_port != 0 && listen_port < IPPORT_RESERVED &&
1163                     pw->pw_uid != 0)
1164 #endif
1165                     ) {
1166                         success = 0;
1167                         packet_send_debug("Server has disabled port forwarding.");
1168                 } else {
1169                         /* Start listening on the port */
1170                         success = channel_setup_remote_fwd_listener(
1171                             listen_address, listen_port,
1172                             &allocated_listen_port, options.gateway_ports);
1173                 }
1174                 xfree(listen_address);
1175         } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1176                 char *cancel_address;
1177                 u_short cancel_port;
1178
1179                 cancel_address = packet_get_string(NULL);
1180                 cancel_port = (u_short)packet_get_int();
1181                 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1182                     cancel_address, cancel_port);
1183
1184                 success = channel_cancel_rport_listener(cancel_address,
1185                     cancel_port);
1186                 xfree(cancel_address);
1187         } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
1188                 no_more_sessions = 1;
1189                 success = 1;
1190         }
1191         if (want_reply) {
1192                 packet_start(success ?
1193                     SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1194                 if (success && allocated_listen_port > 0)
1195                         packet_put_int(allocated_listen_port);
1196                 packet_send();
1197                 packet_write_wait();
1198         }
1199         xfree(rtype);
1200 }
1201
1202 static void
1203 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1204 {
1205         Channel *c;
1206         int id, reply, success = 0;
1207         char *rtype;
1208
1209         id = packet_get_int();
1210         rtype = packet_get_string(NULL);
1211         reply = packet_get_char();
1212
1213         debug("server_input_channel_req: channel %d request %s reply %d",
1214             id, rtype, reply);
1215
1216         if ((c = channel_lookup(id)) == NULL)
1217                 packet_disconnect("server_input_channel_req: "
1218                     "unknown channel %d", id);
1219         if (!strcmp(rtype, "eow@openssh.com")) {
1220                 packet_check_eom();
1221                 chan_rcvd_eow(c);
1222         } else if ((c->type == SSH_CHANNEL_LARVAL ||
1223             c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
1224                 success = session_input_channel_req(c, rtype);
1225         if (reply) {
1226                 packet_start(success ?
1227                     SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1228                 packet_put_int(c->remote_id);
1229                 packet_send();
1230         }
1231         xfree(rtype);
1232 }
1233
1234 static void
1235 server_init_dispatch_20(void)
1236 {
1237         debug("server_init_dispatch_20");
1238         dispatch_init(&dispatch_protocol_error);
1239         dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1240         dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1241         dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1242         dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1243         dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1244         dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1245         dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1246         dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1247         dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1248         dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1249         /* client_alive */
1250         dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
1251         dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1252         dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1253         dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1254         /* rekeying */
1255         dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1256 }
1257 static void
1258 server_init_dispatch_13(void)
1259 {
1260         debug("server_init_dispatch_13");
1261         dispatch_init(NULL);
1262         dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1263         dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1264         dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1265         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1266         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1267         dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1268         dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1269         dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1270         dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1271 }
1272 static void
1273 server_init_dispatch_15(void)
1274 {
1275         server_init_dispatch_13();
1276         debug("server_init_dispatch_15");
1277         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1278         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1279 }
1280 static void
1281 server_init_dispatch(void)
1282 {
1283         if (compat20)
1284                 server_init_dispatch_20();
1285         else if (compat13)
1286                 server_init_dispatch_13();
1287         else
1288                 server_init_dispatch_15();
1289 }