]> andersk Git - openssh.git/blob - serverloop.c
2afca7637039345b82d766314378004442be0575
[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  * Created: Sun Sep 10 00:30:37 1995 ylo
6  * Server main loop for handling the interactive session.
7  */
8
9 #include "includes.h"
10 #include "xmalloc.h"
11 #include "ssh.h"
12 #include "packet.h"
13 #include "buffer.h"
14 #include "servconf.h"
15 #include "pty.h"
16
17 static Buffer stdin_buffer;     /* Buffer for stdin data. */
18 static Buffer stdout_buffer;    /* Buffer for stdout data. */
19 static Buffer stderr_buffer;    /* Buffer for stderr data. */
20 static int fdin;                /* Descriptor for stdin (for writing) */
21 static int fdout;               /* Descriptor for stdout (for reading);
22                                    May be same number as fdin. */
23 static int fderr;               /* Descriptor for stderr.  May be -1. */
24 static long stdin_bytes = 0;    /* Number of bytes written to stdin. */
25 static long stdout_bytes = 0;   /* Number of stdout bytes sent to client. */
26 static long stderr_bytes = 0;   /* Number of stderr bytes sent to client. */
27 static long fdout_bytes = 0;    /* Number of stdout bytes read from program. */
28 static int stdin_eof = 0;       /* EOF message received from client. */
29 static int fdout_eof = 0;       /* EOF encountered reading from fdout. */
30 static int fderr_eof = 0;       /* EOF encountered readung from fderr. */
31 static int connection_in;       /* Connection to client (input). */
32 static int connection_out;      /* Connection to client (output). */
33 static unsigned int buffer_high;/* "Soft" max buffer size. */
34 static int max_fd;              /* Max file descriptor number for select(). */
35
36 /*
37  * This SIGCHLD kludge is used to detect when the child exits.  The server
38  * will exit after that, as soon as forwarded connections have terminated.
39  *
40  * After SIGCHLD child_has_selected is set to 1 after the first pass
41  * through the wait_until_can_do_something() select(). This ensures
42  * that the child's output gets a chance to drain before it is yanked.
43  */
44
45 static int child_pid;                   /* Pid of the child. */
46 static volatile int child_terminated;   /* The child has terminated. */
47 static volatile int child_has_selected; /* Child has had chance to drain. */
48 static volatile int child_wait_status;  /* Status from wait(). */
49
50 void 
51 sigchld_handler(int sig)
52 {
53         int save_errno = errno;
54         int wait_pid;
55         debug("Received SIGCHLD.");
56         wait_pid = wait((int *) &child_wait_status);
57         if (wait_pid != -1) {
58                 if (wait_pid != child_pid)
59                         error("Strange, got SIGCHLD and wait returned pid %d but child is %d",
60                               wait_pid, child_pid);
61                 if (WIFEXITED(child_wait_status) ||
62                     WIFSIGNALED(child_wait_status))
63                         child_terminated = 1;
64                         child_has_selected = 0;
65         }
66         signal(SIGCHLD, sigchld_handler);
67         errno = save_errno;
68 }
69
70 /*
71  * Process any buffered packets that have been received from the client.
72  */
73 void 
74 process_buffered_input_packets()
75 {
76         int type;
77         char *data;
78         unsigned int data_len;
79         int row, col, xpixel, ypixel;
80         int payload_len;
81
82         /* Process buffered packets from the client. */
83         while ((type = packet_read_poll(&payload_len)) != SSH_MSG_NONE) {
84                 switch (type) {
85                 case SSH_CMSG_STDIN_DATA:
86                         /* Stdin data from the client.  Append it to the buffer. */
87                         /* Ignore any data if the client has closed stdin. */
88                         if (fdin == -1)
89                                 break;
90                         data = packet_get_string(&data_len);
91                         packet_integrity_check(payload_len, (4 + data_len), type);
92                         buffer_append(&stdin_buffer, data, data_len);
93                         memset(data, 0, data_len);
94                         xfree(data);
95                         break;
96
97                 case SSH_CMSG_EOF:
98                         /*
99                          * Eof from the client.  The stdin descriptor to the
100                          * program will be closed when all buffered data has
101                          * drained.
102                          */
103                         debug("EOF received for stdin.");
104                         packet_integrity_check(payload_len, 0, type);
105                         stdin_eof = 1;
106                         break;
107
108                 case SSH_CMSG_WINDOW_SIZE:
109                         debug("Window change received.");
110                         packet_integrity_check(payload_len, 4 * 4, type);
111                         row = packet_get_int();
112                         col = packet_get_int();
113                         xpixel = packet_get_int();
114                         ypixel = packet_get_int();
115                         if (fdin != -1)
116                                 pty_change_window_size(fdin, row, col, xpixel, ypixel);
117                         break;
118
119                 case SSH_MSG_PORT_OPEN:
120                         debug("Received port open request.");
121                         channel_input_port_open(payload_len);
122                         break;
123
124                 case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
125                         debug("Received channel open confirmation.");
126                         packet_integrity_check(payload_len, 4 + 4, type);
127                         channel_input_open_confirmation();
128                         break;
129
130                 case SSH_MSG_CHANNEL_OPEN_FAILURE:
131                         debug("Received channel open failure.");
132                         packet_integrity_check(payload_len, 4, type);
133                         channel_input_open_failure();
134                         break;
135
136                 case SSH_MSG_CHANNEL_DATA:
137                         channel_input_data(payload_len);
138                         break;
139
140                 case SSH_MSG_CHANNEL_CLOSE:
141                         debug("Received channel close.");
142                         packet_integrity_check(payload_len, 4, type);
143                         channel_input_close();
144                         break;
145
146                 case SSH_MSG_CHANNEL_CLOSE_CONFIRMATION:
147                         debug("Received channel close confirmation.");
148                         packet_integrity_check(payload_len, 4, type);
149                         channel_input_close_confirmation();
150                         break;
151
152                 default:
153                         /*
154                          * In this phase, any unexpected messages cause a
155                          * protocol error.  This is to ease debugging; also,
156                          * since no confirmations are sent messages,
157                          * unprocessed unknown messages could cause strange
158                          * problems.  Any compatible protocol extensions must
159                          * be negotiated before entering the interactive
160                          * session.
161                          */
162                         packet_disconnect("Protocol error during session: type %d",
163                                           type);
164                 }
165         }
166 }
167
168 /*
169  * Make packets from buffered stderr data, and buffer it for sending
170  * to the client.
171  */
172 void 
173 make_packets_from_stderr_data()
174 {
175         int len;
176
177         /* Send buffered stderr data to the client. */
178         while (buffer_len(&stderr_buffer) > 0 &&
179             packet_not_very_much_data_to_write()) {
180                 len = buffer_len(&stderr_buffer);
181                 if (packet_is_interactive()) {
182                         if (len > 512)
183                                 len = 512;
184                 } else {
185                         /* Keep the packets at reasonable size. */
186                         if (len > packet_get_maxsize())
187                                 len = packet_get_maxsize();
188                 }
189                 packet_start(SSH_SMSG_STDERR_DATA);
190                 packet_put_string(buffer_ptr(&stderr_buffer), len);
191                 packet_send();
192                 buffer_consume(&stderr_buffer, len);
193                 stderr_bytes += len;
194         }
195 }
196
197 /*
198  * Make packets from buffered stdout data, and buffer it for sending to the
199  * client.
200  */
201 void 
202 make_packets_from_stdout_data()
203 {
204         int len;
205
206         /* Send buffered stdout data to the client. */
207         while (buffer_len(&stdout_buffer) > 0 &&
208             packet_not_very_much_data_to_write()) {
209                 len = buffer_len(&stdout_buffer);
210                 if (packet_is_interactive()) {
211                         if (len > 512)
212                                 len = 512;
213                 } else {
214                         /* Keep the packets at reasonable size. */
215                         if (len > packet_get_maxsize())
216                                 len = packet_get_maxsize();     
217                 }
218                 packet_start(SSH_SMSG_STDOUT_DATA);
219                 packet_put_string(buffer_ptr(&stdout_buffer), len);
220                 packet_send();
221                 buffer_consume(&stdout_buffer, len);
222                 stdout_bytes += len;
223         }
224 }
225
226 /*
227  * Sleep in select() until we can do something.  This will initialize the
228  * select masks.  Upon return, the masks will indicate which descriptors
229  * have data or can accept data.  Optionally, a maximum time can be specified
230  * for the duration of the wait (0 = infinite).
231  */
232 void 
233 wait_until_can_do_something(fd_set * readset, fd_set * writeset,
234                             unsigned int max_time_milliseconds)
235 {
236         struct timeval tv, *tvp;
237         int ret;
238
239         /* When select fails we restart from here. */
240 retry_select:
241
242         /* Initialize select() masks. */
243         FD_ZERO(readset);
244
245         /*
246          * Read packets from the client unless we have too much buffered
247          * stdin or channel data.
248          */
249         if (buffer_len(&stdin_buffer) < 4096 &&
250             channel_not_very_much_buffered_data())
251                 FD_SET(connection_in, readset);
252
253         /*
254          * If there is not too much data already buffered going to the
255          * client, try to get some more data from the program.
256          */
257         if (packet_not_very_much_data_to_write()) {
258                 if (!fdout_eof)
259                         FD_SET(fdout, readset);
260                 if (!fderr_eof)
261                         FD_SET(fderr, readset);
262         }
263         FD_ZERO(writeset);
264
265         /* Set masks for channel descriptors. */
266         channel_prepare_select(readset, writeset);
267
268         /*
269          * If we have buffered packet data going to the client, mark that
270          * descriptor.
271          */
272         if (packet_have_data_to_write())
273                 FD_SET(connection_out, writeset);
274
275         /* If we have buffered data, try to write some of that data to the
276            program. */
277         if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
278                 FD_SET(fdin, writeset);
279
280         /* Update the maximum descriptor number if appropriate. */
281         if (channel_max_fd() > max_fd)
282                 max_fd = channel_max_fd();
283
284         /*
285          * If child has terminated and there is enough buffer space to read
286          * from it, then read as much as is available and exit.
287          */
288         if (child_terminated && packet_not_very_much_data_to_write())
289                 if (max_time_milliseconds == 0)
290                         max_time_milliseconds = 100;
291
292         if (max_time_milliseconds == 0)
293                 tvp = NULL;
294         else {
295                 tv.tv_sec = max_time_milliseconds / 1000;
296                 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
297                 tvp = &tv;
298         }
299
300         /* Wait for something to happen, or the timeout to expire. */
301         ret = select(max_fd + 1, readset, writeset, NULL, tvp);
302
303         if (ret < 0) {
304                 if (errno != EINTR)
305                         error("select: %.100s", strerror(errno));
306                 else
307                         goto retry_select;
308         }
309         
310         if (child_terminated)
311                 child_has_selected = 1;
312 }
313
314 /*
315  * Processes input from the client and the program.  Input data is stored
316  * in buffers and processed later.
317  */
318 void 
319 process_input(fd_set * readset)
320 {
321         int len;
322         char buf[16384];
323
324         /* Read and buffer any input data from the client. */
325         if (FD_ISSET(connection_in, readset)) {
326                 len = read(connection_in, buf, sizeof(buf));
327                 if (len == 0) {
328                         verbose("Connection closed by remote host.");
329                         fatal_cleanup();
330                 }
331                 /*
332                  * There is a kernel bug on Solaris that causes select to
333                  * sometimes wake up even though there is no data available.
334                  */
335                 if (len < 0 && errno == EAGAIN)
336                         len = 0;
337
338                 if (len < 0) {
339                         verbose("Read error from remote host: %.100s", strerror(errno));
340                         fatal_cleanup();
341                 }
342                 /* Buffer any received data. */
343                 packet_process_incoming(buf, len);
344         }
345         /* Read and buffer any available stdout data from the program. */
346         if (!fdout_eof && FD_ISSET(fdout, readset)) {
347                 len = read(fdout, buf, sizeof(buf));
348                 if (len <= 0)
349                         fdout_eof = 1;
350                 else {
351                         buffer_append(&stdout_buffer, buf, len);
352                         fdout_bytes += len;
353                 }
354         }
355         /* Read and buffer any available stderr data from the program. */
356         if (!fderr_eof && FD_ISSET(fderr, readset)) {
357                 len = read(fderr, buf, sizeof(buf));
358                 if (len <= 0)
359                         fderr_eof = 1;
360                 else
361                         buffer_append(&stderr_buffer, buf, len);
362         }
363 }
364
365 /*
366  * Sends data from internal buffers to client program stdin.
367  */
368 void 
369 process_output(fd_set * writeset)
370 {
371         int len;
372
373         /* Write buffered data to program stdin. */
374         if (fdin != -1 && FD_ISSET(fdin, writeset)) {
375                 len = write(fdin, buffer_ptr(&stdin_buffer),
376                     buffer_len(&stdin_buffer));
377                 if (len <= 0) {
378 #ifdef USE_PIPES
379                         close(fdin);
380 #else
381                         if (fdout == -1)
382                                 close(fdin);
383                         else
384                                 shutdown(fdin, SHUT_WR); /* We will no longer send. */
385 #endif
386                         fdin = -1;
387                 } else {
388                         /* Successful write.  Consume the data from the buffer. */
389                         buffer_consume(&stdin_buffer, len);
390                         /* Update the count of bytes written to the program. */
391                         stdin_bytes += len;
392                 }
393         }
394         /* Send any buffered packet data to the client. */
395         if (FD_ISSET(connection_out, writeset))
396                 packet_write_poll();
397 }
398
399 /*
400  * Wait until all buffered output has been sent to the client.
401  * This is used when the program terminates.
402  */
403 void 
404 drain_output()
405 {
406         /* Send any buffered stdout data to the client. */
407         if (buffer_len(&stdout_buffer) > 0) {
408                 packet_start(SSH_SMSG_STDOUT_DATA);
409                 packet_put_string(buffer_ptr(&stdout_buffer),
410                                   buffer_len(&stdout_buffer));
411                 packet_send();
412                 /* Update the count of sent bytes. */
413                 stdout_bytes += buffer_len(&stdout_buffer);
414         }
415         /* Send any buffered stderr data to the client. */
416         if (buffer_len(&stderr_buffer) > 0) {
417                 packet_start(SSH_SMSG_STDERR_DATA);
418                 packet_put_string(buffer_ptr(&stderr_buffer),
419                                   buffer_len(&stderr_buffer));
420                 packet_send();
421                 /* Update the count of sent bytes. */
422                 stderr_bytes += buffer_len(&stderr_buffer);
423         }
424         /* Wait until all buffered data has been written to the client. */
425         packet_write_wait();
426 }
427
428 /*
429  * Performs the interactive session.  This handles data transmission between
430  * the client and the program.  Note that the notion of stdin, stdout, and
431  * stderr in this function is sort of reversed: this function writes to
432  * stdin (of the child program), and reads from stdout and stderr (of the
433  * child program).
434  */
435 void 
436 server_loop(int pid, int fdin_arg, int fdout_arg, int fderr_arg)
437 {
438         int wait_status, wait_pid;      /* Status and pid returned by wait(). */
439         int waiting_termination = 0;    /* Have displayed waiting close message. */
440         unsigned int max_time_milliseconds;
441         unsigned int previous_stdout_buffer_bytes;
442         unsigned int stdout_buffer_bytes;
443         int type;
444
445         debug("Entering interactive session.");
446
447         /* Initialize the SIGCHLD kludge. */
448         child_pid = pid;
449         child_terminated = 0;
450         child_has_selected = 0;
451         signal(SIGCHLD, sigchld_handler);
452
453         /* Initialize our global variables. */
454         fdin = fdin_arg;
455         fdout = fdout_arg;
456         fderr = fderr_arg;
457         connection_in = packet_get_connection_in();
458         connection_out = packet_get_connection_out();
459
460         previous_stdout_buffer_bytes = 0;
461
462         /* Set approximate I/O buffer size. */
463         if (packet_is_interactive())
464                 buffer_high = 4096;
465         else
466                 buffer_high = 64 * 1024;
467
468         /* Initialize max_fd to the maximum of the known file descriptors. */
469         max_fd = fdin;
470         if (fdout > max_fd)
471                 max_fd = fdout;
472         if (fderr != -1 && fderr > max_fd)
473                 max_fd = fderr;
474         if (connection_in > max_fd)
475                 max_fd = connection_in;
476         if (connection_out > max_fd)
477                 max_fd = connection_out;
478
479         /* Initialize Initialize buffers. */
480         buffer_init(&stdin_buffer);
481         buffer_init(&stdout_buffer);
482         buffer_init(&stderr_buffer);
483
484         /*
485          * If we have no separate fderr (which is the case when we have a pty
486          * - there we cannot make difference between data sent to stdout and
487          * stderr), indicate that we have seen an EOF from stderr.  This way
488          * we don\'t need to check the descriptor everywhere.
489          */
490         if (fderr == -1)
491                 fderr_eof = 1;
492
493         /* Main loop of the server for the interactive session mode. */
494         for (;;) {
495                 fd_set readset, writeset;
496
497                 /* Process buffered packets from the client. */
498                 process_buffered_input_packets();
499
500                 /*
501                  * If we have received eof, and there is no more pending
502                  * input data, cause a real eof by closing fdin.
503                  */
504                 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
505 #ifdef USE_PIPES
506                         close(fdin);
507 #else
508                         if (fdout == -1)
509                                 close(fdin);
510                         else
511                                 shutdown(fdin, SHUT_WR); /* We will no longer send. */
512 #endif
513                         fdin = -1;
514                 }
515                 /* Make packets from buffered stderr data to send to the client. */
516                 make_packets_from_stderr_data();
517
518                 /*
519                  * Make packets from buffered stdout data to send to the
520                  * client. If there is very little to send, this arranges to
521                  * not send them now, but to wait a short while to see if we
522                  * are getting more data. This is necessary, as some systems
523                  * wake up readers from a pty after each separate character.
524                  */
525                 max_time_milliseconds = 0;
526                 stdout_buffer_bytes = buffer_len(&stdout_buffer);
527                 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
528                     stdout_buffer_bytes != previous_stdout_buffer_bytes) {
529                         /* try again after a while */
530                         max_time_milliseconds = 10;
531                 } else {
532                         /* Send it now. */
533                         make_packets_from_stdout_data();
534                 }
535                 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
536
537                 /* Send channel data to the client. */
538                 if (packet_not_very_much_data_to_write())
539                         channel_output_poll();
540
541                 /*
542                  * Bail out of the loop if the program has closed its output
543                  * descriptors, and we have no more data to send to the
544                  * client, and there is no pending buffered data.
545                  */
546                 if (((fdout_eof && fderr_eof) || 
547                     (child_terminated && child_has_selected)) && 
548                     !packet_have_data_to_write() &&
549                     (buffer_len(&stdout_buffer) == 0) && 
550                          (buffer_len(&stderr_buffer) == 0)) {
551                         if (!channel_still_open())
552                                 goto quit;
553                         if (!waiting_termination) {
554                                 const char *s = "Waiting for forwarded connections to terminate...\r\n";
555                                 char *cp;
556                                 waiting_termination = 1;
557                                 buffer_append(&stderr_buffer, s, strlen(s));
558
559                                 /* Display list of open channels. */
560                                 cp = channel_open_message();
561                                 buffer_append(&stderr_buffer, cp, strlen(cp));
562                                 xfree(cp);
563                         }
564                 }
565                 /* Sleep in select() until we can do something. */
566                 wait_until_can_do_something(&readset, &writeset,
567                                             max_time_milliseconds);
568
569                 /* Process any channel events. */
570                 channel_after_select(&readset, &writeset);
571
572                 /* Process input from the client and from program stdout/stderr. */
573                 process_input(&readset);
574
575                 /* Process output to the client and to program stdin. */
576                 process_output(&writeset);
577         }
578
579 quit:
580         /* Cleanup and termination code. */
581
582         /* Wait until all output has been sent to the client. */
583         drain_output();
584
585         debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
586               stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
587
588         /* Free and clear the buffers. */
589         buffer_free(&stdin_buffer);
590         buffer_free(&stdout_buffer);
591         buffer_free(&stderr_buffer);
592
593         /* Close the file descriptors. */
594         if (fdout != -1)
595                 close(fdout);
596         fdout = -1;
597         fdout_eof = 1;
598         if (fderr != -1)
599                 close(fderr);
600         fderr = -1;
601         fderr_eof = 1;
602         if (fdin != -1)
603                 close(fdin);
604         fdin = -1;
605
606         /* Stop listening for channels; this removes unix domain sockets. */
607         channel_stop_listening();
608
609         /* Wait for the child to exit.  Get its exit status. */
610         wait_pid = wait(&wait_status);
611         if (wait_pid < 0) {
612                 /*
613                  * It is possible that the wait was handled by SIGCHLD
614                  * handler.  This may result in either: this call
615                  * returning with EINTR, or: this call returning ECHILD.
616                  */
617                 if (child_terminated)
618                         wait_status = child_wait_status;
619                 else
620                         packet_disconnect("wait: %.100s", strerror(errno));
621         } else {
622                 /* Check if it matches the process we forked. */
623                 if (wait_pid != pid)
624                         error("Strange, wait returned pid %d, expected %d",
625                                wait_pid, pid);
626         }
627
628         /* We no longer want our SIGCHLD handler to be called. */
629         signal(SIGCHLD, SIG_DFL);
630
631         /* Check if it exited normally. */
632         if (WIFEXITED(wait_status)) {
633                 /* Yes, normal exit.  Get exit status and send it to the client. */
634                 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
635                 packet_start(SSH_SMSG_EXITSTATUS);
636                 packet_put_int(WEXITSTATUS(wait_status));
637                 packet_send();
638                 packet_write_wait();
639
640                 /*
641                  * Wait for exit confirmation.  Note that there might be
642                  * other packets coming before it; however, the program has
643                  * already died so we just ignore them.  The client is
644                  * supposed to respond with the confirmation when it receives
645                  * the exit status.
646                  */
647                 do {
648                         int plen;
649                         type = packet_read(&plen);
650                 }
651                 while (type != SSH_CMSG_EXIT_CONFIRMATION);
652
653                 debug("Received exit confirmation.");
654                 return;
655         }
656         /* Check if the program terminated due to a signal. */
657         if (WIFSIGNALED(wait_status))
658                 packet_disconnect("Command terminated on signal %d.",
659                                   WTERMSIG(wait_status));
660
661         /* Some weird exit cause.  Just exit. */
662         packet_disconnect("wait returned status %04x.", wait_status);
663         /* NOTREACHED */
664 }
This page took 0.08181 seconds and 3 git commands to generate.