]> andersk Git - openssh.git/blob - serverloop.c
- (djm) Merge OpenBSD changes:
[openssh.git] / serverloop.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Server main loop for handling the interactive session.
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  *
13  * SSH2 support by Markus Friedl.
14  * Copyright (c) 2000 Markus Friedl. All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #include "includes.h"
38 RCSID("$OpenBSD: serverloop.c,v 1.35 2000/11/06 23:04:56 markus Exp $");
39
40 #include "xmalloc.h"
41 #include "ssh.h"
42 #include "packet.h"
43 #include "buffer.h"
44 #include "servconf.h"
45 #include "pty.h"
46 #include "channels.h"
47
48 #include "compat.h"
49 #include "ssh2.h"
50 #include "session.h"
51 #include "dispatch.h"
52 #include "auth-options.h"
53 #include "auth.h"
54
55 extern ServerOptions options;
56
57 static Buffer stdin_buffer;     /* Buffer for stdin data. */
58 static Buffer stdout_buffer;    /* Buffer for stdout data. */
59 static Buffer stderr_buffer;    /* Buffer for stderr data. */
60 static int fdin;                /* Descriptor for stdin (for writing) */
61 static int fdout;               /* Descriptor for stdout (for reading);
62                                    May be same number as fdin. */
63 static int fderr;               /* Descriptor for stderr.  May be -1. */
64 static long stdin_bytes = 0;    /* Number of bytes written to stdin. */
65 static long stdout_bytes = 0;   /* Number of stdout bytes sent to client. */
66 static long stderr_bytes = 0;   /* Number of stderr bytes sent to client. */
67 static long fdout_bytes = 0;    /* Number of stdout bytes read from program. */
68 static int stdin_eof = 0;       /* EOF message received from client. */
69 static int fdout_eof = 0;       /* EOF encountered reading from fdout. */
70 static int fderr_eof = 0;       /* EOF encountered readung from fderr. */
71 static int connection_in;       /* Connection to client (input). */
72 static int connection_out;      /* Connection to client (output). */
73 static unsigned int buffer_high;/* "Soft" max buffer size. */
74 static int max_fd;              /* Max file descriptor number for select(). */
75
76 /*
77  * This SIGCHLD kludge is used to detect when the child exits.  The server
78  * will exit after that, as soon as forwarded connections have terminated.
79  *
80  * After SIGCHLD child_has_selected is set to 1 after the first pass
81  * through the wait_until_can_do_something() select(). This ensures
82  * that the child's output gets a chance to drain before it is yanked.
83  */
84
85 static pid_t child_pid;                 /* Pid of the child. */
86 static volatile int child_terminated;   /* The child has terminated. */
87 static volatile int child_has_selected; /* Child has had chance to drain. */
88 static volatile int child_wait_status;  /* Status from wait(). */
89
90 void    server_init_dispatch(void);
91
92 void
93 sigchld_handler(int sig)
94 {
95         int save_errno = errno;
96         pid_t wait_pid;
97
98         debug("Received SIGCHLD.");
99         wait_pid = wait((int *) &child_wait_status);
100         if (wait_pid != -1) {
101                 if (wait_pid != child_pid)
102                         error("Strange, got SIGCHLD and wait returned pid %d but child is %d",
103                               wait_pid, child_pid);
104                 if (WIFEXITED(child_wait_status) ||
105                     WIFSIGNALED(child_wait_status)) {
106                         child_terminated = 1;
107                         child_has_selected = 0;
108                 }
109         }
110         signal(SIGCHLD, sigchld_handler);
111         errno = save_errno;
112 }
113 void
114 sigchld_handler2(int sig)
115 {
116         int save_errno = errno;
117         debug("Received SIGCHLD.");
118         child_terminated = 1;
119         child_has_selected = 0;
120         errno = save_errno;
121 }
122
123 /*
124  * Make packets from buffered stderr data, and buffer it for sending
125  * to the client.
126  */
127 void
128 make_packets_from_stderr_data()
129 {
130         int len;
131
132         /* Send buffered stderr data to the client. */
133         while (buffer_len(&stderr_buffer) > 0 &&
134             packet_not_very_much_data_to_write()) {
135                 len = buffer_len(&stderr_buffer);
136                 if (packet_is_interactive()) {
137                         if (len > 512)
138                                 len = 512;
139                 } else {
140                         /* Keep the packets at reasonable size. */
141                         if (len > packet_get_maxsize())
142                                 len = packet_get_maxsize();
143                 }
144                 packet_start(SSH_SMSG_STDERR_DATA);
145                 packet_put_string(buffer_ptr(&stderr_buffer), len);
146                 packet_send();
147                 buffer_consume(&stderr_buffer, len);
148                 stderr_bytes += len;
149         }
150 }
151
152 /*
153  * Make packets from buffered stdout data, and buffer it for sending to the
154  * client.
155  */
156 void
157 make_packets_from_stdout_data()
158 {
159         int len;
160
161         /* Send buffered stdout data to the client. */
162         while (buffer_len(&stdout_buffer) > 0 &&
163             packet_not_very_much_data_to_write()) {
164                 len = buffer_len(&stdout_buffer);
165                 if (packet_is_interactive()) {
166                         if (len > 512)
167                                 len = 512;
168                 } else {
169                         /* Keep the packets at reasonable size. */
170                         if (len > packet_get_maxsize())
171                                 len = packet_get_maxsize();     
172                 }
173                 packet_start(SSH_SMSG_STDOUT_DATA);
174                 packet_put_string(buffer_ptr(&stdout_buffer), len);
175                 packet_send();
176                 buffer_consume(&stdout_buffer, len);
177                 stdout_bytes += len;
178         }
179 }
180
181 /*
182  * Sleep in select() until we can do something.  This will initialize the
183  * select masks.  Upon return, the masks will indicate which descriptors
184  * have data or can accept data.  Optionally, a maximum time can be specified
185  * for the duration of the wait (0 = infinite).
186  */
187 void
188 wait_until_can_do_something(fd_set * readset, fd_set * writeset,
189                             unsigned int max_time_milliseconds)
190 {
191         struct timeval tv, *tvp;
192         int ret;
193
194         /* When select fails we restart from here. */
195 retry_select:
196
197         /* Initialize select() masks. */
198         FD_ZERO(readset);
199         FD_ZERO(writeset);
200
201         if (compat20) {
202                 /* wrong: bad condition XXX */
203                 if (channel_not_very_much_buffered_data())
204                         FD_SET(connection_in, readset);
205         } else {
206                 /*
207                  * Read packets from the client unless we have too much
208                  * buffered stdin or channel data.
209                  */
210                 if (buffer_len(&stdin_buffer) < buffer_high &&
211                     channel_not_very_much_buffered_data())
212                         FD_SET(connection_in, readset);
213                 /*
214                  * If there is not too much data already buffered going to
215                  * the client, try to get some more data from the program.
216                  */
217                 if (packet_not_very_much_data_to_write()) {
218                         if (!fdout_eof)
219                                 FD_SET(fdout, readset);
220                         if (!fderr_eof)
221                                 FD_SET(fderr, readset);
222                 }
223                 /*
224                  * If we have buffered data, try to write some of that data
225                  * to the program.
226                  */
227                 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
228                         FD_SET(fdin, writeset);
229         }
230         /* Set masks for channel descriptors. */
231         channel_prepare_select(readset, writeset);
232
233         /*
234          * If we have buffered packet data going to the client, mark that
235          * descriptor.
236          */
237         if (packet_have_data_to_write())
238                 FD_SET(connection_out, writeset);
239
240         /* Update the maximum descriptor number if appropriate. */
241         if (channel_max_fd() > max_fd)
242                 max_fd = channel_max_fd();
243
244         /*
245          * If child has terminated and there is enough buffer space to read
246          * from it, then read as much as is available and exit.
247          */
248         if (child_terminated && packet_not_very_much_data_to_write())
249                 if (max_time_milliseconds == 0)
250                         max_time_milliseconds = 100;
251
252         if (max_time_milliseconds == 0)
253                 tvp = NULL;
254         else {
255                 tv.tv_sec = max_time_milliseconds / 1000;
256                 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
257                 tvp = &tv;
258         }
259         if (tvp!=NULL)
260                 debug("tvp!=NULL kid %d mili %d", child_terminated, max_time_milliseconds);
261
262         /* Wait for something to happen, or the timeout to expire. */
263         ret = select(max_fd + 1, readset, writeset, NULL, tvp);
264
265         if (ret < 0) {
266                 if (errno != EINTR)
267                         error("select: %.100s", strerror(errno));
268                 else
269                         goto retry_select;
270         }
271         
272         if (child_terminated)
273                 child_has_selected = 1;
274 }
275
276 /*
277  * Processes input from the client and the program.  Input data is stored
278  * in buffers and processed later.
279  */
280 void
281 process_input(fd_set * readset)
282 {
283         int len;
284         char buf[16384];
285
286         /* Read and buffer any input data from the client. */
287         if (FD_ISSET(connection_in, readset)) {
288                 len = read(connection_in, buf, sizeof(buf));
289                 if (len == 0) {
290                         verbose("Connection closed by remote host.");
291                         fatal_cleanup();
292                 } else if (len < 0) {
293                         if (errno != EINTR && errno != EAGAIN) {
294                                 verbose("Read error from remote host: %.100s", strerror(errno));
295                                 fatal_cleanup();
296                         }
297                 } else {
298                         /* Buffer any received data. */
299                         packet_process_incoming(buf, len);
300                 }
301         }
302         if (compat20)
303                 return;
304
305         /* Read and buffer any available stdout data from the program. */
306         if (!fdout_eof && FD_ISSET(fdout, readset)) {
307                 len = read(fdout, buf, sizeof(buf));
308                 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
309                         /* do nothing */
310                 } else if (len <= 0) {
311                         fdout_eof = 1;
312                 } else {
313                         buffer_append(&stdout_buffer, buf, len);
314                         fdout_bytes += len;
315                 }
316         }
317         /* Read and buffer any available stderr data from the program. */
318         if (!fderr_eof && FD_ISSET(fderr, readset)) {
319                 len = read(fderr, buf, sizeof(buf));
320                 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
321                         /* do nothing */
322                 } else if (len <= 0) {
323                         fderr_eof = 1;
324                 } else {
325                         buffer_append(&stderr_buffer, buf, len);
326                 }
327         }
328 }
329
330 /*
331  * Sends data from internal buffers to client program stdin.
332  */
333 void
334 process_output(fd_set * writeset)
335 {
336         int len;
337
338         /* Write buffered data to program stdin. */
339         if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
340                 len = write(fdin, buffer_ptr(&stdin_buffer),
341                     buffer_len(&stdin_buffer));
342                 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
343                         /* do nothing */
344                 } else if (len <= 0) {
345 #ifdef USE_PIPES
346                         close(fdin);
347 #else
348                         if (fdin != fdout)
349                                 close(fdin);
350                         else
351                                 shutdown(fdin, SHUT_WR); /* We will no longer send. */
352 #endif
353                         fdin = -1;
354                 } else {
355                         /* Successful write.  Consume the data from the buffer. */
356                         buffer_consume(&stdin_buffer, len);
357                         /* Update the count of bytes written to the program. */
358                         stdin_bytes += len;
359                 }
360         }
361         /* Send any buffered packet data to the client. */
362         if (FD_ISSET(connection_out, writeset))
363                 packet_write_poll();
364 }
365
366 /*
367  * Wait until all buffered output has been sent to the client.
368  * This is used when the program terminates.
369  */
370 void
371 drain_output()
372 {
373         /* Send any buffered stdout data to the client. */
374         if (buffer_len(&stdout_buffer) > 0) {
375                 packet_start(SSH_SMSG_STDOUT_DATA);
376                 packet_put_string(buffer_ptr(&stdout_buffer),
377                                   buffer_len(&stdout_buffer));
378                 packet_send();
379                 /* Update the count of sent bytes. */
380                 stdout_bytes += buffer_len(&stdout_buffer);
381         }
382         /* Send any buffered stderr data to the client. */
383         if (buffer_len(&stderr_buffer) > 0) {
384                 packet_start(SSH_SMSG_STDERR_DATA);
385                 packet_put_string(buffer_ptr(&stderr_buffer),
386                                   buffer_len(&stderr_buffer));
387                 packet_send();
388                 /* Update the count of sent bytes. */
389                 stderr_bytes += buffer_len(&stderr_buffer);
390         }
391         /* Wait until all buffered data has been written to the client. */
392         packet_write_wait();
393 }
394
395 void
396 process_buffered_input_packets()
397 {
398         dispatch_run(DISPATCH_NONBLOCK, NULL, NULL);
399 }
400
401 /*
402  * Performs the interactive session.  This handles data transmission between
403  * the client and the program.  Note that the notion of stdin, stdout, and
404  * stderr in this function is sort of reversed: this function writes to
405  * stdin (of the child program), and reads from stdout and stderr (of the
406  * child program).
407  */
408 void
409 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
410 {
411         fd_set readset, writeset;
412         int wait_status;        /* Status returned by wait(). */
413         pid_t wait_pid;         /* pid returned by wait(). */
414         int waiting_termination = 0;    /* Have displayed waiting close message. */
415         unsigned int max_time_milliseconds;
416         unsigned int previous_stdout_buffer_bytes;
417         unsigned int stdout_buffer_bytes;
418         int type;
419
420         debug("Entering interactive session.");
421
422         /* Initialize the SIGCHLD kludge. */
423         child_pid = pid;
424         child_terminated = 0;
425         child_has_selected = 0;
426         signal(SIGCHLD, sigchld_handler);
427         signal(SIGPIPE, SIG_IGN);
428
429         /* Initialize our global variables. */
430         fdin = fdin_arg;
431         fdout = fdout_arg;
432         fderr = fderr_arg;
433
434         /* nonblocking IO */
435         set_nonblock(fdin);
436         set_nonblock(fdout);
437         /* we don't have stderr for interactive terminal sessions, see below */
438         if (fderr != -1)
439                 set_nonblock(fderr);
440
441         connection_in = packet_get_connection_in();
442         connection_out = packet_get_connection_out();
443
444         previous_stdout_buffer_bytes = 0;
445
446         /* Set approximate I/O buffer size. */
447         if (packet_is_interactive())
448                 buffer_high = 4096;
449         else
450                 buffer_high = 64 * 1024;
451
452         /* Initialize max_fd to the maximum of the known file descriptors. */
453         max_fd = fdin;
454         if (fdout > max_fd)
455                 max_fd = fdout;
456         if (fderr != -1 && fderr > max_fd)
457                 max_fd = fderr;
458         if (connection_in > max_fd)
459                 max_fd = connection_in;
460         if (connection_out > max_fd)
461                 max_fd = connection_out;
462
463         /* Initialize Initialize buffers. */
464         buffer_init(&stdin_buffer);
465         buffer_init(&stdout_buffer);
466         buffer_init(&stderr_buffer);
467
468         /*
469          * If we have no separate fderr (which is the case when we have a pty
470          * - there we cannot make difference between data sent to stdout and
471          * stderr), indicate that we have seen an EOF from stderr.  This way
472          * we don\'t need to check the descriptor everywhere.
473          */
474         if (fderr == -1)
475                 fderr_eof = 1;
476
477         server_init_dispatch();
478
479         /* Main loop of the server for the interactive session mode. */
480         for (;;) {
481
482                 /* Process buffered packets from the client. */
483                 process_buffered_input_packets();
484
485                 /*
486                  * If we have received eof, and there is no more pending
487                  * input data, cause a real eof by closing fdin.
488                  */
489                 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
490 #ifdef USE_PIPES
491                         close(fdin);
492 #else
493                         if (fdin != fdout)
494                                 close(fdin);
495                         else
496                                 shutdown(fdin, SHUT_WR); /* We will no longer send. */
497 #endif
498                         fdin = -1;
499                 }
500                 /* Make packets from buffered stderr data to send to the client. */
501                 make_packets_from_stderr_data();
502
503                 /*
504                  * Make packets from buffered stdout data to send to the
505                  * client. If there is very little to send, this arranges to
506                  * not send them now, but to wait a short while to see if we
507                  * are getting more data. This is necessary, as some systems
508                  * wake up readers from a pty after each separate character.
509                  */
510                 max_time_milliseconds = 0;
511                 stdout_buffer_bytes = buffer_len(&stdout_buffer);
512                 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
513                     stdout_buffer_bytes != previous_stdout_buffer_bytes) {
514                         /* try again after a while */
515                         max_time_milliseconds = 10;
516                 } else {
517                         /* Send it now. */
518                         make_packets_from_stdout_data();
519                 }
520                 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
521
522                 /* Send channel data to the client. */
523                 if (packet_not_very_much_data_to_write())
524                         channel_output_poll();
525
526                 /*
527                  * Bail out of the loop if the program has closed its output
528                  * descriptors, and we have no more data to send to the
529                  * client, and there is no pending buffered data.
530                  */
531                 if (((fdout_eof && fderr_eof) || 
532                     (child_terminated && child_has_selected)) && 
533                     !packet_have_data_to_write() &&
534                     (buffer_len(&stdout_buffer) == 0) && 
535                          (buffer_len(&stderr_buffer) == 0)) {
536                         if (!channel_still_open())
537                                 break;
538                         if (!waiting_termination) {
539                                 const char *s = "Waiting for forwarded connections to terminate...\r\n";
540                                 char *cp;
541                                 waiting_termination = 1;
542                                 buffer_append(&stderr_buffer, s, strlen(s));
543
544                                 /* Display list of open channels. */
545                                 cp = channel_open_message();
546                                 buffer_append(&stderr_buffer, cp, strlen(cp));
547                                 xfree(cp);
548                         }
549                 }
550                 /* Sleep in select() until we can do something. */
551                 wait_until_can_do_something(&readset, &writeset,
552                                             max_time_milliseconds);
553
554                 /* Process any channel events. */
555                 channel_after_select(&readset, &writeset);
556
557                 /* Process input from the client and from program stdout/stderr. */
558                 process_input(&readset);
559
560                 /* Process output to the client and to program stdin. */
561                 process_output(&writeset);
562         }
563
564         /* Cleanup and termination code. */
565
566         /* Wait until all output has been sent to the client. */
567         drain_output();
568
569         debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
570               stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
571
572         /* Free and clear the buffers. */
573         buffer_free(&stdin_buffer);
574         buffer_free(&stdout_buffer);
575         buffer_free(&stderr_buffer);
576
577         /* Close the file descriptors. */
578         if (fdout != -1)
579                 close(fdout);
580         fdout = -1;
581         fdout_eof = 1;
582         if (fderr != -1)
583                 close(fderr);
584         fderr = -1;
585         fderr_eof = 1;
586         if (fdin != -1)
587                 close(fdin);
588         fdin = -1;
589
590         /* Stop listening for channels; this removes unix domain sockets. */
591         channel_stop_listening();
592
593         /* Wait for the child to exit.  Get its exit status. */
594         wait_pid = wait(&wait_status);
595         if (wait_pid < 0) {
596                 /*
597                  * It is possible that the wait was handled by SIGCHLD
598                  * handler.  This may result in either: this call
599                  * returning with EINTR, or: this call returning ECHILD.
600                  */
601                 if (child_terminated)
602                         wait_status = child_wait_status;
603                 else
604                         packet_disconnect("wait: %.100s", strerror(errno));
605         } else {
606                 /* Check if it matches the process we forked. */
607                 if (wait_pid != pid)
608                         error("Strange, wait returned pid %d, expected %d",
609                                wait_pid, pid);
610         }
611
612         /* We no longer want our SIGCHLD handler to be called. */
613         signal(SIGCHLD, SIG_DFL);
614
615         /* Check if it exited normally. */
616         if (WIFEXITED(wait_status)) {
617                 /* Yes, normal exit.  Get exit status and send it to the client. */
618                 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
619                 packet_start(SSH_SMSG_EXITSTATUS);
620                 packet_put_int(WEXITSTATUS(wait_status));
621                 packet_send();
622                 packet_write_wait();
623
624                 /*
625                  * Wait for exit confirmation.  Note that there might be
626                  * other packets coming before it; however, the program has
627                  * already died so we just ignore them.  The client is
628                  * supposed to respond with the confirmation when it receives
629                  * the exit status.
630                  */
631                 do {
632                         int plen;
633                         type = packet_read(&plen);
634                 }
635                 while (type != SSH_CMSG_EXIT_CONFIRMATION);
636
637                 debug("Received exit confirmation.");
638                 return;
639         }
640         /* Check if the program terminated due to a signal. */
641         if (WIFSIGNALED(wait_status))
642                 packet_disconnect("Command terminated on signal %d.",
643                                   WTERMSIG(wait_status));
644
645         /* Some weird exit cause.  Just exit. */
646         packet_disconnect("wait returned status %04x.", wait_status);
647         /* NOTREACHED */
648 }
649
650 void
651 server_loop2(void)
652 {
653         fd_set readset, writeset;
654         int had_channel = 0;
655         int status;
656         pid_t pid;
657
658         debug("Entering interactive session for SSH2.");
659
660         signal(SIGCHLD, sigchld_handler2);
661         signal(SIGPIPE, SIG_IGN);
662         child_terminated = 0;
663         connection_in = packet_get_connection_in();
664         connection_out = packet_get_connection_out();
665         max_fd = connection_in;
666         if (connection_out > max_fd)
667                 max_fd = connection_out;
668         server_init_dispatch();
669
670         for (;;) {
671                 process_buffered_input_packets();
672                 if (!had_channel && channel_still_open())
673                         had_channel = 1;
674                 if (had_channel && !channel_still_open()) {
675                         debug("!channel_still_open.");
676                         break;
677                 }
678                 if (packet_not_very_much_data_to_write())
679                         channel_output_poll();
680                 wait_until_can_do_something(&readset, &writeset, 0);
681                 if (child_terminated && child_has_selected) {
682                         /* XXX: race - assumes only one child has terminated */
683                         while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
684                                 session_close_by_pid(pid, status);
685                         child_terminated = 0;
686                         child_has_selected = 0;
687                         signal(SIGCHLD, sigchld_handler2);
688                 }
689                 channel_after_select(&readset, &writeset);
690                 process_input(&readset);
691                 process_output(&writeset);
692         }
693         signal(SIGCHLD, SIG_DFL);
694         while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
695                 session_close_by_pid(pid, status);
696         channel_stop_listening();
697 }
698
699 void
700 server_input_stdin_data(int type, int plen, void *ctxt)
701 {
702         char *data;
703         unsigned int data_len;
704
705         /* Stdin data from the client.  Append it to the buffer. */
706         /* Ignore any data if the client has closed stdin. */
707         if (fdin == -1)
708                 return;
709         data = packet_get_string(&data_len);
710         packet_integrity_check(plen, (4 + data_len), type);
711         buffer_append(&stdin_buffer, data, data_len);
712         memset(data, 0, data_len);
713         xfree(data);
714 }
715
716 void
717 server_input_eof(int type, int plen, void *ctxt)
718 {
719         /*
720          * Eof from the client.  The stdin descriptor to the
721          * program will be closed when all buffered data has
722          * drained.
723          */
724         debug("EOF received for stdin.");
725         packet_integrity_check(plen, 0, type);
726         stdin_eof = 1;
727 }
728
729 void
730 server_input_window_size(int type, int plen, void *ctxt)
731 {
732         int row = packet_get_int();
733         int col = packet_get_int();
734         int xpixel = packet_get_int();
735         int ypixel = packet_get_int();
736
737         debug("Window change received.");
738         packet_integrity_check(plen, 4 * 4, type);
739         if (fdin != -1)
740                 pty_change_window_size(fdin, row, col, xpixel, ypixel);
741 }
742
743 Channel *
744 server_request_direct_tcpip(char *ctype)
745 {
746         int sock, newch;
747         char *target, *originator;
748         int target_port, originator_port;
749
750         target = packet_get_string(NULL);
751         target_port = packet_get_int();
752         originator = packet_get_string(NULL);
753         originator_port = packet_get_int();
754         packet_done();
755
756         debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
757            originator, originator_port, target, target_port);
758
759         /* XXX check permission */
760         if (no_port_forwarding_flag || !options.allow_tcp_forwarding) {
761                 xfree(target);
762                 xfree(originator);
763                 return NULL;
764         }
765         sock = channel_connect_to(target, target_port);
766         xfree(target);
767         xfree(originator);
768         if (sock < 0)
769                 return NULL;
770         newch = channel_new(ctype, SSH_CHANNEL_OPEN,
771             sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
772             CHAN_TCP_PACKET_DEFAULT, 0, xstrdup("direct-tcpip"), 1);
773         return (newch >= 0) ? channel_lookup(newch) : NULL;
774 }
775
776 Channel *
777 server_request_session(char *ctype)
778 {
779         int newch;
780
781         debug("input_session_request");
782         packet_done();
783         /*
784          * A server session has no fd to read or write until a
785          * CHANNEL_REQUEST for a shell is made, so we set the type to
786          * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
787          * CHANNEL_REQUEST messages is registered.
788          */
789         newch = channel_new(ctype, SSH_CHANNEL_LARVAL,
790             -1, -1, -1, 0, CHAN_SES_PACKET_DEFAULT,
791             0, xstrdup("server-session"), 1);
792         if (session_open(newch) == 1) {
793                 channel_register_callback(newch, SSH2_MSG_CHANNEL_REQUEST,
794                     session_input_channel_req, (void *)0);
795                 channel_register_cleanup(newch, session_close_by_channel);
796                 return channel_lookup(newch);
797         } else {
798                 debug("session open failed, free channel %d", newch);
799                 channel_free(newch);
800         }
801         return NULL;
802 }
803
804 void
805 server_input_channel_open(int type, int plen, void *ctxt)
806 {
807         Channel *c = NULL;
808         char *ctype;
809         unsigned int len;
810         int rchan;
811         int rmaxpack;
812         int rwindow;
813
814         ctype = packet_get_string(&len);
815         rchan = packet_get_int();
816         rwindow = packet_get_int();
817         rmaxpack = packet_get_int();
818
819         debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
820             ctype, rchan, rwindow, rmaxpack);
821
822         if (strcmp(ctype, "session") == 0) {
823                 c = server_request_session(ctype);
824         } else if (strcmp(ctype, "direct-tcpip") == 0) {
825                 c = server_request_direct_tcpip(ctype);
826         }
827         if (c != NULL) {
828                 debug("server_input_channel_open: confirm %s", ctype);
829                 c->remote_id = rchan;
830                 c->remote_window = rwindow;
831                 c->remote_maxpacket = rmaxpack;
832
833                 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
834                 packet_put_int(c->remote_id);
835                 packet_put_int(c->self);
836                 packet_put_int(c->local_window);
837                 packet_put_int(c->local_maxpacket);
838                 packet_send();
839         } else {
840                 debug("server_input_channel_open: failure %s", ctype);
841                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
842                 packet_put_int(rchan);
843                 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
844                 packet_put_cstring("bla bla");
845                 packet_put_cstring("");
846                 packet_send();
847         }
848         xfree(ctype);
849 }
850
851 void 
852 server_input_global_request(int type, int plen, void *ctxt)
853 {
854         char *rtype;
855         int want_reply;
856         int success = 0;
857
858         rtype = packet_get_string(NULL);
859         want_reply = packet_get_char();
860         debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
861         
862         if (strcmp(rtype, "tcpip-forward") == 0) {
863                 struct passwd *pw;
864                 char *listen_address;
865                 u_short listen_port;
866
867                 pw = auth_get_user();
868                 if (pw == NULL)
869                         fatal("server_input_global_request: no user");
870                 listen_address = packet_get_string(NULL); /* XXX currently ignored */
871                 listen_port = (u_short)packet_get_int();
872                 debug("server_input_global_request: tcpip-forward listen %s port %d",
873                     listen_address, listen_port);
874
875                 /* check permissions */
876                 if (!options.allow_tcp_forwarding ||
877                     no_port_forwarding_flag ||
878                     (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)) {
879                         success = 0;
880                         packet_send_debug("Server has disabled port forwarding.");
881                 } else {
882                         /* Start listening on the port */
883                         channel_request_forwarding(
884                             listen_address, listen_port,
885                             /*unspec host_to_connect*/ "<unspec host>",
886                             /*unspec port_to_connect*/ 0,
887                             options.gateway_ports, /*remote*/ 1);
888                         success = 1;
889                 }
890                 xfree(listen_address);
891         }
892         if (want_reply) {
893                 packet_start(success ?
894                     SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
895                 packet_send();
896                 packet_write_wait();
897         }
898         xfree(rtype);
899 }
900
901 void
902 server_init_dispatch_20()
903 {
904         debug("server_init_dispatch_20");
905         dispatch_init(&dispatch_protocol_error);
906         dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
907         dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
908         dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
909         dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
910         dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
911         dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
912         dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
913         dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &channel_input_channel_request);
914         dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
915         dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
916 }
917 void
918 server_init_dispatch_13()
919 {
920         debug("server_init_dispatch_13");
921         dispatch_init(NULL);
922         dispatch_set(SSH_CMSG_EOF, &server_input_eof);
923         dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
924         dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
925         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
926         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
927         dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
928         dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
929         dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
930         dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
931 }
932 void
933 server_init_dispatch_15()
934 {
935         server_init_dispatch_13();
936         debug("server_init_dispatch_15");
937         dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
938         dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
939 }
940 void
941 server_init_dispatch()
942 {
943         if (compat20)
944                 server_init_dispatch_20();
945         else if (compat13)
946                 server_init_dispatch_13();
947         else
948                 server_init_dispatch_15();
949 }
This page took 0.138331 seconds and 5 git commands to generate.