2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Sun Sep 10 00:30:37 1995 ylo
6 * Server main loop for handling the interactive session.
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(). */
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.
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.
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(). */
51 sigchld_handler(int sig)
53 int save_errno = errno;
55 debug("Received SIGCHLD.");
56 wait_pid = wait((int *) &child_wait_status);
58 if (wait_pid != child_pid)
59 error("Strange, got SIGCHLD and wait returned pid %d but child is %d",
61 if (WIFEXITED(child_wait_status) ||
62 WIFSIGNALED(child_wait_status))
64 child_has_selected = 0;
66 signal(SIGCHLD, sigchld_handler);
71 * Process any buffered packets that have been received from the client.
74 process_buffered_input_packets()
78 unsigned int data_len;
79 int row, col, xpixel, ypixel;
82 /* Process buffered packets from the client. */
83 while ((type = packet_read_poll(&payload_len)) != SSH_MSG_NONE) {
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. */
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);
99 * Eof from the client. The stdin descriptor to the
100 * program will be closed when all buffered data has
103 debug("EOF received for stdin.");
104 packet_integrity_check(payload_len, 0, type);
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();
116 pty_change_window_size(fdin, row, col, xpixel, ypixel);
119 case SSH_MSG_PORT_OPEN:
120 debug("Received port open request.");
121 channel_input_port_open(payload_len);
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();
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();
136 case SSH_MSG_CHANNEL_DATA:
137 channel_input_data(payload_len);
140 case SSH_MSG_CHANNEL_CLOSE:
141 debug("Received channel close.");
142 packet_integrity_check(payload_len, 4, type);
143 channel_input_close();
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();
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
162 packet_disconnect("Protocol error during session: type %d",
169 * Make packets from buffered stderr data, and buffer it for sending
173 make_packets_from_stderr_data()
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()) {
185 /* Keep the packets at reasonable size. */
186 if (len > packet_get_maxsize())
187 len = packet_get_maxsize();
189 packet_start(SSH_SMSG_STDERR_DATA);
190 packet_put_string(buffer_ptr(&stderr_buffer), len);
192 buffer_consume(&stderr_buffer, len);
198 * Make packets from buffered stdout data, and buffer it for sending to the
202 make_packets_from_stdout_data()
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()) {
214 /* Keep the packets at reasonable size. */
215 if (len > packet_get_maxsize())
216 len = packet_get_maxsize();
218 packet_start(SSH_SMSG_STDOUT_DATA);
219 packet_put_string(buffer_ptr(&stdout_buffer), len);
221 buffer_consume(&stdout_buffer, len);
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).
233 wait_until_can_do_something(fd_set * readset, fd_set * writeset,
234 unsigned int max_time_milliseconds)
236 struct timeval tv, *tvp;
239 /* When select fails we restart from here. */
242 /* Initialize select() masks. */
246 * Read packets from the client unless we have too much buffered
247 * stdin or channel data.
249 if (buffer_len(&stdin_buffer) < 4096 &&
250 channel_not_very_much_buffered_data())
251 FD_SET(connection_in, readset);
254 * If there is not too much data already buffered going to the
255 * client, try to get some more data from the program.
257 if (packet_not_very_much_data_to_write()) {
259 FD_SET(fdout, readset);
261 FD_SET(fderr, readset);
265 /* Set masks for channel descriptors. */
266 channel_prepare_select(readset, writeset);
269 * If we have buffered packet data going to the client, mark that
272 if (packet_have_data_to_write())
273 FD_SET(connection_out, writeset);
275 /* If we have buffered data, try to write some of that data to the
277 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
278 FD_SET(fdin, writeset);
280 /* Update the maximum descriptor number if appropriate. */
281 if (channel_max_fd() > max_fd)
282 max_fd = channel_max_fd();
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.
288 if (child_terminated && packet_not_very_much_data_to_write())
289 if (max_time_milliseconds == 0)
290 max_time_milliseconds = 100;
292 if (max_time_milliseconds == 0)
295 tv.tv_sec = max_time_milliseconds / 1000;
296 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
300 /* Wait for something to happen, or the timeout to expire. */
301 ret = select(max_fd + 1, readset, writeset, NULL, tvp);
305 error("select: %.100s", strerror(errno));
310 if (child_terminated)
311 child_has_selected = 1;
315 * Processes input from the client and the program. Input data is stored
316 * in buffers and processed later.
319 process_input(fd_set * readset)
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));
328 verbose("Connection closed by remote host.");
332 * There is a kernel bug on Solaris that causes select to
333 * sometimes wake up even though there is no data available.
335 if (len < 0 && errno == EAGAIN)
339 verbose("Read error from remote host: %.100s", strerror(errno));
342 /* Buffer any received data. */
343 packet_process_incoming(buf, len);
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));
351 buffer_append(&stdout_buffer, buf, len);
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));
361 buffer_append(&stderr_buffer, buf, len);
366 * Sends data from internal buffers to client program stdin.
369 process_output(fd_set * writeset)
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));
384 shutdown(fdin, SHUT_WR); /* We will no longer send. */
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. */
394 /* Send any buffered packet data to the client. */
395 if (FD_ISSET(connection_out, writeset))
400 * Wait until all buffered output has been sent to the client.
401 * This is used when the program terminates.
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));
412 /* Update the count of sent bytes. */
413 stdout_bytes += buffer_len(&stdout_buffer);
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));
421 /* Update the count of sent bytes. */
422 stderr_bytes += buffer_len(&stderr_buffer);
424 /* Wait until all buffered data has been written to the client. */
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
436 server_loop(int pid, int fdin_arg, int fdout_arg, int fderr_arg)
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;
445 debug("Entering interactive session.");
447 /* Initialize the SIGCHLD kludge. */
449 child_terminated = 0;
450 child_has_selected = 0;
451 signal(SIGCHLD, sigchld_handler);
453 /* Initialize our global variables. */
457 connection_in = packet_get_connection_in();
458 connection_out = packet_get_connection_out();
460 previous_stdout_buffer_bytes = 0;
462 /* Set approximate I/O buffer size. */
463 if (packet_is_interactive())
466 buffer_high = 64 * 1024;
468 /* Initialize max_fd to the maximum of the known file descriptors. */
472 if (fderr != -1 && fderr > max_fd)
474 if (connection_in > max_fd)
475 max_fd = connection_in;
476 if (connection_out > max_fd)
477 max_fd = connection_out;
479 /* Initialize Initialize buffers. */
480 buffer_init(&stdin_buffer);
481 buffer_init(&stdout_buffer);
482 buffer_init(&stderr_buffer);
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.
493 /* Main loop of the server for the interactive session mode. */
495 fd_set readset, writeset;
497 /* Process buffered packets from the client. */
498 process_buffered_input_packets();
501 * If we have received eof, and there is no more pending
502 * input data, cause a real eof by closing fdin.
504 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
511 shutdown(fdin, SHUT_WR); /* We will no longer send. */
515 /* Make packets from buffered stderr data to send to the client. */
516 make_packets_from_stderr_data();
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.
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;
533 make_packets_from_stdout_data();
535 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
537 /* Send channel data to the client. */
538 if (packet_not_very_much_data_to_write())
539 channel_output_poll();
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.
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())
553 if (!waiting_termination) {
554 const char *s = "Waiting for forwarded connections to terminate...\r\n";
556 waiting_termination = 1;
557 buffer_append(&stderr_buffer, s, strlen(s));
559 /* Display list of open channels. */
560 cp = channel_open_message();
561 buffer_append(&stderr_buffer, cp, strlen(cp));
565 /* Sleep in select() until we can do something. */
566 wait_until_can_do_something(&readset, &writeset,
567 max_time_milliseconds);
569 /* Process any channel events. */
570 channel_after_select(&readset, &writeset);
572 /* Process input from the client and from program stdout/stderr. */
573 process_input(&readset);
575 /* Process output to the client and to program stdin. */
576 process_output(&writeset);
580 /* Cleanup and termination code. */
582 /* Wait until all output has been sent to the client. */
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);
588 /* Free and clear the buffers. */
589 buffer_free(&stdin_buffer);
590 buffer_free(&stdout_buffer);
591 buffer_free(&stderr_buffer);
593 /* Close the file descriptors. */
606 /* Stop listening for channels; this removes unix domain sockets. */
607 channel_stop_listening();
609 /* Wait for the child to exit. Get its exit status. */
610 wait_pid = wait(&wait_status);
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.
617 if (child_terminated)
618 wait_status = child_wait_status;
620 packet_disconnect("wait: %.100s", strerror(errno));
622 /* Check if it matches the process we forked. */
624 error("Strange, wait returned pid %d, expected %d",
628 /* We no longer want our SIGCHLD handler to be called. */
629 signal(SIGCHLD, SIG_DFL);
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));
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
649 type = packet_read(&plen);
651 while (type != SSH_CMSG_EXIT_CONFIRMATION);
653 debug("Received exit confirmation.");
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));
661 /* Some weird exit cause. Just exit. */
662 packet_disconnect("wait returned status %04x.", wait_status);