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