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