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