- djm@cvs.openbsd.org 2006/07/10 11:25:53
[openssh-git.git] / serverloop.c
blob09063ab8c8d8589448bc24527f91e314c3c85f58
1 /* $OpenBSD: serverloop.c,v 1.138 2006/07/09 15:15:11 stevesk Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Server main loop for handling the interactive session.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
14 * SSH2 support by Markus Friedl.
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include "includes.h"
40 #include <sys/types.h>
41 #include <sys/wait.h>
42 #include <sys/socket.h>
44 #include <netinet/in.h>
46 #include <fcntl.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <termios.h>
51 #include "xmalloc.h"
52 #include "packet.h"
53 #include "buffer.h"
54 #include "log.h"
55 #include "servconf.h"
56 #include "canohost.h"
57 #include "sshpty.h"
58 #include "channels.h"
59 #include "compat.h"
60 #include "ssh1.h"
61 #include "ssh2.h"
62 #include "auth.h"
63 #include "session.h"
64 #include "dispatch.h"
65 #include "auth-options.h"
66 #include "serverloop.h"
67 #include "misc.h"
68 #include "kex.h"
70 extern ServerOptions options;
72 /* XXX */
73 extern Kex *xxx_kex;
74 extern Authctxt *the_authctxt;
75 extern int use_privsep;
77 static Buffer stdin_buffer; /* Buffer for stdin data. */
78 static Buffer stdout_buffer; /* Buffer for stdout data. */
79 static Buffer stderr_buffer; /* Buffer for stderr data. */
80 static int fdin; /* Descriptor for stdin (for writing) */
81 static int fdout; /* Descriptor for stdout (for reading);
82 May be same number as fdin. */
83 static int fderr; /* Descriptor for stderr. May be -1. */
84 static long stdin_bytes = 0; /* Number of bytes written to stdin. */
85 static long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
86 static long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
87 static long fdout_bytes = 0; /* Number of stdout bytes read from program. */
88 static int stdin_eof = 0; /* EOF message received from client. */
89 static int fdout_eof = 0; /* EOF encountered reading from fdout. */
90 static int fderr_eof = 0; /* EOF encountered readung from fderr. */
91 static int fdin_is_tty = 0; /* fdin points to a tty. */
92 static int connection_in; /* Connection to client (input). */
93 static int connection_out; /* Connection to client (output). */
94 static int connection_closed = 0; /* Connection to client closed. */
95 static u_int buffer_high; /* "Soft" max buffer size. */
96 static int client_alive_timeouts = 0;
99 * This SIGCHLD kludge is used to detect when the child exits. The server
100 * will exit after that, as soon as forwarded connections have terminated.
103 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */
105 /* Cleanup on signals (!use_privsep case only) */
106 static volatile sig_atomic_t received_sigterm = 0;
108 /* prototypes */
109 static void server_init_dispatch(void);
112 * we write to this pipe if a SIGCHLD is caught in order to avoid
113 * the race between select() and child_terminated
115 static int notify_pipe[2];
116 static void
117 notify_setup(void)
119 if (pipe(notify_pipe) < 0) {
120 error("pipe(notify_pipe) failed %s", strerror(errno));
121 } else if ((fcntl(notify_pipe[0], F_SETFD, 1) == -1) ||
122 (fcntl(notify_pipe[1], F_SETFD, 1) == -1)) {
123 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
124 close(notify_pipe[0]);
125 close(notify_pipe[1]);
126 } else {
127 set_nonblock(notify_pipe[0]);
128 set_nonblock(notify_pipe[1]);
129 return;
131 notify_pipe[0] = -1; /* read end */
132 notify_pipe[1] = -1; /* write end */
134 static void
135 notify_parent(void)
137 if (notify_pipe[1] != -1)
138 write(notify_pipe[1], "", 1);
140 static void
141 notify_prepare(fd_set *readset)
143 if (notify_pipe[0] != -1)
144 FD_SET(notify_pipe[0], readset);
146 static void
147 notify_done(fd_set *readset)
149 char c;
151 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
152 while (read(notify_pipe[0], &c, 1) != -1)
153 debug2("notify_done: reading");
156 /*ARGSUSED*/
157 static void
158 sigchld_handler(int sig)
160 int save_errno = errno;
161 child_terminated = 1;
162 #ifndef _UNICOS
163 mysignal(SIGCHLD, sigchld_handler);
164 #endif
165 notify_parent();
166 errno = save_errno;
169 /*ARGSUSED*/
170 static void
171 sigterm_handler(int sig)
173 received_sigterm = sig;
177 * Make packets from buffered stderr data, and buffer it for sending
178 * to the client.
180 static void
181 make_packets_from_stderr_data(void)
183 u_int len;
185 /* Send buffered stderr data to the client. */
186 while (buffer_len(&stderr_buffer) > 0 &&
187 packet_not_very_much_data_to_write()) {
188 len = buffer_len(&stderr_buffer);
189 if (packet_is_interactive()) {
190 if (len > 512)
191 len = 512;
192 } else {
193 /* Keep the packets at reasonable size. */
194 if (len > packet_get_maxsize())
195 len = packet_get_maxsize();
197 packet_start(SSH_SMSG_STDERR_DATA);
198 packet_put_string(buffer_ptr(&stderr_buffer), len);
199 packet_send();
200 buffer_consume(&stderr_buffer, len);
201 stderr_bytes += len;
206 * Make packets from buffered stdout data, and buffer it for sending to the
207 * client.
209 static void
210 make_packets_from_stdout_data(void)
212 u_int len;
214 /* Send buffered stdout data to the client. */
215 while (buffer_len(&stdout_buffer) > 0 &&
216 packet_not_very_much_data_to_write()) {
217 len = buffer_len(&stdout_buffer);
218 if (packet_is_interactive()) {
219 if (len > 512)
220 len = 512;
221 } else {
222 /* Keep the packets at reasonable size. */
223 if (len > packet_get_maxsize())
224 len = packet_get_maxsize();
226 packet_start(SSH_SMSG_STDOUT_DATA);
227 packet_put_string(buffer_ptr(&stdout_buffer), len);
228 packet_send();
229 buffer_consume(&stdout_buffer, len);
230 stdout_bytes += len;
234 static void
235 client_alive_check(void)
237 int channel_id;
239 /* timeout, check to see how many we have had */
240 if (++client_alive_timeouts > options.client_alive_count_max)
241 packet_disconnect("Timeout, your session not responding.");
244 * send a bogus global/channel request with "wantreply",
245 * we should get back a failure
247 if ((channel_id = channel_find_open()) == -1) {
248 packet_start(SSH2_MSG_GLOBAL_REQUEST);
249 packet_put_cstring("keepalive@openssh.com");
250 packet_put_char(1); /* boolean: want reply */
251 } else {
252 channel_request_start(channel_id, "keepalive@openssh.com", 1);
254 packet_send();
258 * Sleep in select() until we can do something. This will initialize the
259 * select masks. Upon return, the masks will indicate which descriptors
260 * have data or can accept data. Optionally, a maximum time can be specified
261 * for the duration of the wait (0 = infinite).
263 static void
264 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
265 u_int *nallocp, u_int max_time_milliseconds)
267 struct timeval tv, *tvp;
268 int ret;
269 int client_alive_scheduled = 0;
272 * if using client_alive, set the max timeout accordingly,
273 * and indicate that this particular timeout was for client
274 * alive by setting the client_alive_scheduled flag.
276 * this could be randomized somewhat to make traffic
277 * analysis more difficult, but we're not doing it yet.
279 if (compat20 &&
280 max_time_milliseconds == 0 && options.client_alive_interval) {
281 client_alive_scheduled = 1;
282 max_time_milliseconds = options.client_alive_interval * 1000;
285 /* Allocate and update select() masks for channel descriptors. */
286 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
288 if (compat20) {
289 #if 0
290 /* wrong: bad condition XXX */
291 if (channel_not_very_much_buffered_data())
292 #endif
293 FD_SET(connection_in, *readsetp);
294 } else {
296 * Read packets from the client unless we have too much
297 * buffered stdin or channel data.
299 if (buffer_len(&stdin_buffer) < buffer_high &&
300 channel_not_very_much_buffered_data())
301 FD_SET(connection_in, *readsetp);
303 * If there is not too much data already buffered going to
304 * the client, try to get some more data from the program.
306 if (packet_not_very_much_data_to_write()) {
307 if (!fdout_eof)
308 FD_SET(fdout, *readsetp);
309 if (!fderr_eof)
310 FD_SET(fderr, *readsetp);
313 * If we have buffered data, try to write some of that data
314 * to the program.
316 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
317 FD_SET(fdin, *writesetp);
319 notify_prepare(*readsetp);
322 * If we have buffered packet data going to the client, mark that
323 * descriptor.
325 if (packet_have_data_to_write())
326 FD_SET(connection_out, *writesetp);
329 * If child has terminated and there is enough buffer space to read
330 * from it, then read as much as is available and exit.
332 if (child_terminated && packet_not_very_much_data_to_write())
333 if (max_time_milliseconds == 0 || client_alive_scheduled)
334 max_time_milliseconds = 100;
336 if (max_time_milliseconds == 0)
337 tvp = NULL;
338 else {
339 tv.tv_sec = max_time_milliseconds / 1000;
340 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
341 tvp = &tv;
344 /* Wait for something to happen, or the timeout to expire. */
345 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
347 if (ret == -1) {
348 memset(*readsetp, 0, *nallocp);
349 memset(*writesetp, 0, *nallocp);
350 if (errno != EINTR)
351 error("select: %.100s", strerror(errno));
352 } else if (ret == 0 && client_alive_scheduled)
353 client_alive_check();
355 notify_done(*readsetp);
359 * Processes input from the client and the program. Input data is stored
360 * in buffers and processed later.
362 static void
363 process_input(fd_set *readset)
365 int len;
366 char buf[16384];
368 /* Read and buffer any input data from the client. */
369 if (FD_ISSET(connection_in, readset)) {
370 len = read(connection_in, buf, sizeof(buf));
371 if (len == 0) {
372 verbose("Connection closed by %.100s",
373 get_remote_ipaddr());
374 connection_closed = 1;
375 if (compat20)
376 return;
377 cleanup_exit(255);
378 } else if (len < 0) {
379 if (errno != EINTR && errno != EAGAIN) {
380 verbose("Read error from remote host "
381 "%.100s: %.100s",
382 get_remote_ipaddr(), strerror(errno));
383 cleanup_exit(255);
385 } else {
386 /* Buffer any received data. */
387 packet_process_incoming(buf, len);
390 if (compat20)
391 return;
393 /* Read and buffer any available stdout data from the program. */
394 if (!fdout_eof && FD_ISSET(fdout, readset)) {
395 errno = 0;
396 len = read(fdout, buf, sizeof(buf));
397 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
398 /* do nothing */
399 #ifndef PTY_ZEROREAD
400 } else if (len <= 0) {
401 #else
402 } else if ((!isatty(fdout) && len <= 0) ||
403 (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
404 #endif
405 fdout_eof = 1;
406 } else {
407 buffer_append(&stdout_buffer, buf, len);
408 fdout_bytes += len;
411 /* Read and buffer any available stderr data from the program. */
412 if (!fderr_eof && FD_ISSET(fderr, readset)) {
413 errno = 0;
414 len = read(fderr, buf, sizeof(buf));
415 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
416 /* do nothing */
417 #ifndef PTY_ZEROREAD
418 } else if (len <= 0) {
419 #else
420 } else if ((!isatty(fderr) && len <= 0) ||
421 (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
422 #endif
423 fderr_eof = 1;
424 } else {
425 buffer_append(&stderr_buffer, buf, len);
431 * Sends data from internal buffers to client program stdin.
433 static void
434 process_output(fd_set *writeset)
436 struct termios tio;
437 u_char *data;
438 u_int dlen;
439 int len;
441 /* Write buffered data to program stdin. */
442 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
443 data = buffer_ptr(&stdin_buffer);
444 dlen = buffer_len(&stdin_buffer);
445 len = write(fdin, data, dlen);
446 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
447 /* do nothing */
448 } else if (len <= 0) {
449 if (fdin != fdout)
450 close(fdin);
451 else
452 shutdown(fdin, SHUT_WR); /* We will no longer send. */
453 fdin = -1;
454 } else {
455 /* Successful write. */
456 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
457 tcgetattr(fdin, &tio) == 0 &&
458 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
460 * Simulate echo to reduce the impact of
461 * traffic analysis
463 packet_send_ignore(len);
464 packet_send();
466 /* Consume the data from the buffer. */
467 buffer_consume(&stdin_buffer, len);
468 /* Update the count of bytes written to the program. */
469 stdin_bytes += len;
472 /* Send any buffered packet data to the client. */
473 if (FD_ISSET(connection_out, writeset))
474 packet_write_poll();
478 * Wait until all buffered output has been sent to the client.
479 * This is used when the program terminates.
481 static void
482 drain_output(void)
484 /* Send any buffered stdout data to the client. */
485 if (buffer_len(&stdout_buffer) > 0) {
486 packet_start(SSH_SMSG_STDOUT_DATA);
487 packet_put_string(buffer_ptr(&stdout_buffer),
488 buffer_len(&stdout_buffer));
489 packet_send();
490 /* Update the count of sent bytes. */
491 stdout_bytes += buffer_len(&stdout_buffer);
493 /* Send any buffered stderr data to the client. */
494 if (buffer_len(&stderr_buffer) > 0) {
495 packet_start(SSH_SMSG_STDERR_DATA);
496 packet_put_string(buffer_ptr(&stderr_buffer),
497 buffer_len(&stderr_buffer));
498 packet_send();
499 /* Update the count of sent bytes. */
500 stderr_bytes += buffer_len(&stderr_buffer);
502 /* Wait until all buffered data has been written to the client. */
503 packet_write_wait();
506 static void
507 process_buffered_input_packets(void)
509 dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
513 * Performs the interactive session. This handles data transmission between
514 * the client and the program. Note that the notion of stdin, stdout, and
515 * stderr in this function is sort of reversed: this function writes to
516 * stdin (of the child program), and reads from stdout and stderr (of the
517 * child program).
519 void
520 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
522 fd_set *readset = NULL, *writeset = NULL;
523 int max_fd = 0;
524 u_int nalloc = 0;
525 int wait_status; /* Status returned by wait(). */
526 pid_t wait_pid; /* pid returned by wait(). */
527 int waiting_termination = 0; /* Have displayed waiting close message. */
528 u_int max_time_milliseconds;
529 u_int previous_stdout_buffer_bytes;
530 u_int stdout_buffer_bytes;
531 int type;
533 debug("Entering interactive session.");
535 /* Initialize the SIGCHLD kludge. */
536 child_terminated = 0;
537 mysignal(SIGCHLD, sigchld_handler);
539 if (!use_privsep) {
540 signal(SIGTERM, sigterm_handler);
541 signal(SIGINT, sigterm_handler);
542 signal(SIGQUIT, sigterm_handler);
545 /* Initialize our global variables. */
546 fdin = fdin_arg;
547 fdout = fdout_arg;
548 fderr = fderr_arg;
550 /* nonblocking IO */
551 set_nonblock(fdin);
552 set_nonblock(fdout);
553 /* we don't have stderr for interactive terminal sessions, see below */
554 if (fderr != -1)
555 set_nonblock(fderr);
557 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
558 fdin_is_tty = 1;
560 connection_in = packet_get_connection_in();
561 connection_out = packet_get_connection_out();
563 notify_setup();
565 previous_stdout_buffer_bytes = 0;
567 /* Set approximate I/O buffer size. */
568 if (packet_is_interactive())
569 buffer_high = 4096;
570 else
571 buffer_high = 64 * 1024;
573 #if 0
574 /* Initialize max_fd to the maximum of the known file descriptors. */
575 max_fd = MAX(connection_in, connection_out);
576 max_fd = MAX(max_fd, fdin);
577 max_fd = MAX(max_fd, fdout);
578 if (fderr != -1)
579 max_fd = MAX(max_fd, fderr);
580 #endif
582 /* Initialize Initialize buffers. */
583 buffer_init(&stdin_buffer);
584 buffer_init(&stdout_buffer);
585 buffer_init(&stderr_buffer);
588 * If we have no separate fderr (which is the case when we have a pty
589 * - there we cannot make difference between data sent to stdout and
590 * stderr), indicate that we have seen an EOF from stderr. This way
591 * we don't need to check the descriptor everywhere.
593 if (fderr == -1)
594 fderr_eof = 1;
596 server_init_dispatch();
598 /* Main loop of the server for the interactive session mode. */
599 for (;;) {
601 /* Process buffered packets from the client. */
602 process_buffered_input_packets();
605 * If we have received eof, and there is no more pending
606 * input data, cause a real eof by closing fdin.
608 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
609 if (fdin != fdout)
610 close(fdin);
611 else
612 shutdown(fdin, SHUT_WR); /* We will no longer send. */
613 fdin = -1;
615 /* Make packets from buffered stderr data to send to the client. */
616 make_packets_from_stderr_data();
619 * Make packets from buffered stdout data to send to the
620 * client. If there is very little to send, this arranges to
621 * not send them now, but to wait a short while to see if we
622 * are getting more data. This is necessary, as some systems
623 * wake up readers from a pty after each separate character.
625 max_time_milliseconds = 0;
626 stdout_buffer_bytes = buffer_len(&stdout_buffer);
627 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
628 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
629 /* try again after a while */
630 max_time_milliseconds = 10;
631 } else {
632 /* Send it now. */
633 make_packets_from_stdout_data();
635 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
637 /* Send channel data to the client. */
638 if (packet_not_very_much_data_to_write())
639 channel_output_poll();
642 * Bail out of the loop if the program has closed its output
643 * descriptors, and we have no more data to send to the
644 * client, and there is no pending buffered data.
646 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
647 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
648 if (!channel_still_open())
649 break;
650 if (!waiting_termination) {
651 const char *s = "Waiting for forwarded connections to terminate...\r\n";
652 char *cp;
653 waiting_termination = 1;
654 buffer_append(&stderr_buffer, s, strlen(s));
656 /* Display list of open channels. */
657 cp = channel_open_message();
658 buffer_append(&stderr_buffer, cp, strlen(cp));
659 xfree(cp);
662 max_fd = MAX(connection_in, connection_out);
663 max_fd = MAX(max_fd, fdin);
664 max_fd = MAX(max_fd, fdout);
665 max_fd = MAX(max_fd, fderr);
666 max_fd = MAX(max_fd, notify_pipe[0]);
668 /* Sleep in select() until we can do something. */
669 wait_until_can_do_something(&readset, &writeset, &max_fd,
670 &nalloc, max_time_milliseconds);
672 if (received_sigterm) {
673 logit("Exiting on signal %d", received_sigterm);
674 /* Clean up sessions, utmp, etc. */
675 cleanup_exit(255);
678 /* Process any channel events. */
679 channel_after_select(readset, writeset);
681 /* Process input from the client and from program stdout/stderr. */
682 process_input(readset);
684 /* Process output to the client and to program stdin. */
685 process_output(writeset);
687 if (readset)
688 xfree(readset);
689 if (writeset)
690 xfree(writeset);
692 /* Cleanup and termination code. */
694 /* Wait until all output has been sent to the client. */
695 drain_output();
697 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
698 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
700 /* Free and clear the buffers. */
701 buffer_free(&stdin_buffer);
702 buffer_free(&stdout_buffer);
703 buffer_free(&stderr_buffer);
705 /* Close the file descriptors. */
706 if (fdout != -1)
707 close(fdout);
708 fdout = -1;
709 fdout_eof = 1;
710 if (fderr != -1)
711 close(fderr);
712 fderr = -1;
713 fderr_eof = 1;
714 if (fdin != -1)
715 close(fdin);
716 fdin = -1;
718 channel_free_all();
720 /* We no longer want our SIGCHLD handler to be called. */
721 mysignal(SIGCHLD, SIG_DFL);
723 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
724 if (errno != EINTR)
725 packet_disconnect("wait: %.100s", strerror(errno));
726 if (wait_pid != pid)
727 error("Strange, wait returned pid %ld, expected %ld",
728 (long)wait_pid, (long)pid);
730 /* Check if it exited normally. */
731 if (WIFEXITED(wait_status)) {
732 /* Yes, normal exit. Get exit status and send it to the client. */
733 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
734 packet_start(SSH_SMSG_EXITSTATUS);
735 packet_put_int(WEXITSTATUS(wait_status));
736 packet_send();
737 packet_write_wait();
740 * Wait for exit confirmation. Note that there might be
741 * other packets coming before it; however, the program has
742 * already died so we just ignore them. The client is
743 * supposed to respond with the confirmation when it receives
744 * the exit status.
746 do {
747 type = packet_read();
749 while (type != SSH_CMSG_EXIT_CONFIRMATION);
751 debug("Received exit confirmation.");
752 return;
754 /* Check if the program terminated due to a signal. */
755 if (WIFSIGNALED(wait_status))
756 packet_disconnect("Command terminated on signal %d.",
757 WTERMSIG(wait_status));
759 /* Some weird exit cause. Just exit. */
760 packet_disconnect("wait returned status %04x.", wait_status);
761 /* NOTREACHED */
764 static void
765 collect_children(void)
767 pid_t pid;
768 sigset_t oset, nset;
769 int status;
771 /* block SIGCHLD while we check for dead children */
772 sigemptyset(&nset);
773 sigaddset(&nset, SIGCHLD);
774 sigprocmask(SIG_BLOCK, &nset, &oset);
775 if (child_terminated) {
776 debug("Received SIGCHLD.");
777 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
778 (pid < 0 && errno == EINTR))
779 if (pid > 0)
780 session_close_by_pid(pid, status);
781 child_terminated = 0;
783 sigprocmask(SIG_SETMASK, &oset, NULL);
786 void
787 server_loop2(Authctxt *authctxt)
789 fd_set *readset = NULL, *writeset = NULL;
790 int rekeying = 0, max_fd, nalloc = 0;
792 debug("Entering interactive session for SSH2.");
794 mysignal(SIGCHLD, sigchld_handler);
795 child_terminated = 0;
796 connection_in = packet_get_connection_in();
797 connection_out = packet_get_connection_out();
799 if (!use_privsep) {
800 signal(SIGTERM, sigterm_handler);
801 signal(SIGINT, sigterm_handler);
802 signal(SIGQUIT, sigterm_handler);
805 notify_setup();
807 max_fd = MAX(connection_in, connection_out);
808 max_fd = MAX(max_fd, notify_pipe[0]);
810 server_init_dispatch();
812 for (;;) {
813 process_buffered_input_packets();
815 rekeying = (xxx_kex != NULL && !xxx_kex->done);
817 if (!rekeying && packet_not_very_much_data_to_write())
818 channel_output_poll();
819 wait_until_can_do_something(&readset, &writeset, &max_fd,
820 &nalloc, 0);
822 if (received_sigterm) {
823 logit("Exiting on signal %d", received_sigterm);
824 /* Clean up sessions, utmp, etc. */
825 cleanup_exit(255);
828 collect_children();
829 if (!rekeying) {
830 channel_after_select(readset, writeset);
831 if (packet_need_rekeying()) {
832 debug("need rekeying");
833 xxx_kex->done = 0;
834 kex_send_kexinit(xxx_kex);
837 process_input(readset);
838 if (connection_closed)
839 break;
840 process_output(writeset);
842 collect_children();
844 if (readset)
845 xfree(readset);
846 if (writeset)
847 xfree(writeset);
849 /* free all channels, no more reads and writes */
850 channel_free_all();
852 /* free remaining sessions, e.g. remove wtmp entries */
853 session_destroy_all(NULL);
856 static void
857 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
859 debug("Got %d/%u for keepalive", type, seq);
861 * reset timeout, since we got a sane answer from the client.
862 * even if this was generated by something other than
863 * the bogus CHANNEL_REQUEST we send for keepalives.
865 client_alive_timeouts = 0;
868 static void
869 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
871 char *data;
872 u_int data_len;
874 /* Stdin data from the client. Append it to the buffer. */
875 /* Ignore any data if the client has closed stdin. */
876 if (fdin == -1)
877 return;
878 data = packet_get_string(&data_len);
879 packet_check_eom();
880 buffer_append(&stdin_buffer, data, data_len);
881 memset(data, 0, data_len);
882 xfree(data);
885 static void
886 server_input_eof(int type, u_int32_t seq, void *ctxt)
889 * Eof from the client. The stdin descriptor to the
890 * program will be closed when all buffered data has
891 * drained.
893 debug("EOF received for stdin.");
894 packet_check_eom();
895 stdin_eof = 1;
898 static void
899 server_input_window_size(int type, u_int32_t seq, void *ctxt)
901 u_int row = packet_get_int();
902 u_int col = packet_get_int();
903 u_int xpixel = packet_get_int();
904 u_int ypixel = packet_get_int();
906 debug("Window change received.");
907 packet_check_eom();
908 if (fdin != -1)
909 pty_change_window_size(fdin, row, col, xpixel, ypixel);
912 static Channel *
913 server_request_direct_tcpip(void)
915 Channel *c;
916 int sock;
917 char *target, *originator;
918 int target_port, originator_port;
920 target = packet_get_string(NULL);
921 target_port = packet_get_int();
922 originator = packet_get_string(NULL);
923 originator_port = packet_get_int();
924 packet_check_eom();
926 debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
927 originator, originator_port, target, target_port);
929 /* XXX check permission */
930 sock = channel_connect_to(target, target_port);
931 xfree(target);
932 xfree(originator);
933 if (sock < 0)
934 return NULL;
935 c = channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING,
936 sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
937 CHAN_TCP_PACKET_DEFAULT, 0, "direct-tcpip", 1);
938 return c;
941 static Channel *
942 server_request_tun(void)
944 Channel *c = NULL;
945 int mode, tun;
946 int sock;
948 mode = packet_get_int();
949 switch (mode) {
950 case SSH_TUNMODE_POINTOPOINT:
951 case SSH_TUNMODE_ETHERNET:
952 break;
953 default:
954 packet_send_debug("Unsupported tunnel device mode.");
955 return NULL;
957 if ((options.permit_tun & mode) == 0) {
958 packet_send_debug("Server has rejected tunnel device "
959 "forwarding");
960 return NULL;
963 tun = packet_get_int();
964 if (forced_tun_device != -1) {
965 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
966 goto done;
967 tun = forced_tun_device;
969 sock = tun_open(tun, mode);
970 if (sock < 0)
971 goto done;
972 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
973 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
974 c->datagram = 1;
975 #if defined(SSH_TUN_FILTER)
976 if (mode == SSH_TUNMODE_POINTOPOINT)
977 channel_register_filter(c->self, sys_tun_infilter,
978 sys_tun_outfilter);
979 #endif
981 done:
982 if (c == NULL)
983 packet_send_debug("Failed to open the tunnel device.");
984 return c;
987 static Channel *
988 server_request_session(void)
990 Channel *c;
992 debug("input_session_request");
993 packet_check_eom();
995 * A server session has no fd to read or write until a
996 * CHANNEL_REQUEST for a shell is made, so we set the type to
997 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
998 * CHANNEL_REQUEST messages is registered.
1000 c = channel_new("session", SSH_CHANNEL_LARVAL,
1001 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1002 0, "server-session", 1);
1003 if (session_open(the_authctxt, c->self) != 1) {
1004 debug("session open failed, free channel %d", c->self);
1005 channel_free(c);
1006 return NULL;
1008 channel_register_cleanup(c->self, session_close_by_channel, 0);
1009 return c;
1012 static void
1013 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1015 Channel *c = NULL;
1016 char *ctype;
1017 int rchan;
1018 u_int rmaxpack, rwindow, len;
1020 ctype = packet_get_string(&len);
1021 rchan = packet_get_int();
1022 rwindow = packet_get_int();
1023 rmaxpack = packet_get_int();
1025 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1026 ctype, rchan, rwindow, rmaxpack);
1028 if (strcmp(ctype, "session") == 0) {
1029 c = server_request_session();
1030 } else if (strcmp(ctype, "direct-tcpip") == 0) {
1031 c = server_request_direct_tcpip();
1032 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1033 c = server_request_tun();
1035 if (c != NULL) {
1036 debug("server_input_channel_open: confirm %s", ctype);
1037 c->remote_id = rchan;
1038 c->remote_window = rwindow;
1039 c->remote_maxpacket = rmaxpack;
1040 if (c->type != SSH_CHANNEL_CONNECTING) {
1041 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1042 packet_put_int(c->remote_id);
1043 packet_put_int(c->self);
1044 packet_put_int(c->local_window);
1045 packet_put_int(c->local_maxpacket);
1046 packet_send();
1048 } else {
1049 debug("server_input_channel_open: failure %s", ctype);
1050 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1051 packet_put_int(rchan);
1052 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1053 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1054 packet_put_cstring("open failed");
1055 packet_put_cstring("");
1057 packet_send();
1059 xfree(ctype);
1062 static void
1063 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1065 char *rtype;
1066 int want_reply;
1067 int success = 0;
1069 rtype = packet_get_string(NULL);
1070 want_reply = packet_get_char();
1071 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1073 /* -R style forwarding */
1074 if (strcmp(rtype, "tcpip-forward") == 0) {
1075 struct passwd *pw;
1076 char *listen_address;
1077 u_short listen_port;
1079 pw = the_authctxt->pw;
1080 if (pw == NULL || !the_authctxt->valid)
1081 fatal("server_input_global_request: no/invalid user");
1082 listen_address = packet_get_string(NULL);
1083 listen_port = (u_short)packet_get_int();
1084 debug("server_input_global_request: tcpip-forward listen %s port %d",
1085 listen_address, listen_port);
1087 /* check permissions */
1088 if (!options.allow_tcp_forwarding ||
1089 no_port_forwarding_flag
1090 #ifndef NO_IPPORT_RESERVED_CONCEPT
1091 || (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)
1092 #endif
1094 success = 0;
1095 packet_send_debug("Server has disabled port forwarding.");
1096 } else {
1097 /* Start listening on the port */
1098 success = channel_setup_remote_fwd_listener(
1099 listen_address, listen_port, options.gateway_ports);
1101 xfree(listen_address);
1102 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1103 char *cancel_address;
1104 u_short cancel_port;
1106 cancel_address = packet_get_string(NULL);
1107 cancel_port = (u_short)packet_get_int();
1108 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1109 cancel_address, cancel_port);
1111 success = channel_cancel_rport_listener(cancel_address,
1112 cancel_port);
1113 xfree(cancel_address);
1115 if (want_reply) {
1116 packet_start(success ?
1117 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1118 packet_send();
1119 packet_write_wait();
1121 xfree(rtype);
1124 static void
1125 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1127 Channel *c;
1128 int id, reply, success = 0;
1129 char *rtype;
1131 id = packet_get_int();
1132 rtype = packet_get_string(NULL);
1133 reply = packet_get_char();
1135 debug("server_input_channel_req: channel %d request %s reply %d",
1136 id, rtype, reply);
1138 if ((c = channel_lookup(id)) == NULL)
1139 packet_disconnect("server_input_channel_req: "
1140 "unknown channel %d", id);
1141 if (c->type == SSH_CHANNEL_LARVAL || c->type == SSH_CHANNEL_OPEN)
1142 success = session_input_channel_req(c, rtype);
1143 if (reply) {
1144 packet_start(success ?
1145 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1146 packet_put_int(c->remote_id);
1147 packet_send();
1149 xfree(rtype);
1152 static void
1153 server_init_dispatch_20(void)
1155 debug("server_init_dispatch_20");
1156 dispatch_init(&dispatch_protocol_error);
1157 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1158 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1159 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1160 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1161 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1162 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1163 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1164 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1165 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1166 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1167 /* client_alive */
1168 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1169 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1170 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1171 /* rekeying */
1172 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1174 static void
1175 server_init_dispatch_13(void)
1177 debug("server_init_dispatch_13");
1178 dispatch_init(NULL);
1179 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1180 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1181 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1182 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1183 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1184 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1185 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1186 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1187 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1189 static void
1190 server_init_dispatch_15(void)
1192 server_init_dispatch_13();
1193 debug("server_init_dispatch_15");
1194 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1195 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1197 static void
1198 server_init_dispatch(void)
1200 if (compat20)
1201 server_init_dispatch_20();
1202 else if (compat13)
1203 server_init_dispatch_13();
1204 else
1205 server_init_dispatch_15();