1 /* $OpenBSD: serverloop.c,v 1.145 2006/10/11 12:38:03 markus Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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
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.
40 #include <sys/types.h>
41 #include <sys/param.h>
43 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
48 #include <netinet/in.h>
77 #include "auth-options.h"
78 #include "serverloop.h"
81 extern ServerOptions options
;
85 extern Authctxt
*the_authctxt
;
86 extern int use_privsep
;
88 static Buffer stdin_buffer
; /* Buffer for stdin data. */
89 static Buffer stdout_buffer
; /* Buffer for stdout data. */
90 static Buffer stderr_buffer
; /* Buffer for stderr data. */
91 static int fdin
; /* Descriptor for stdin (for writing) */
92 static int fdout
; /* Descriptor for stdout (for reading);
93 May be same number as fdin. */
94 static int fderr
; /* Descriptor for stderr. May be -1. */
95 static long stdin_bytes
= 0; /* Number of bytes written to stdin. */
96 static long stdout_bytes
= 0; /* Number of stdout bytes sent to client. */
97 static long stderr_bytes
= 0; /* Number of stderr bytes sent to client. */
98 static long fdout_bytes
= 0; /* Number of stdout bytes read from program. */
99 static int stdin_eof
= 0; /* EOF message received from client. */
100 static int fdout_eof
= 0; /* EOF encountered reading from fdout. */
101 static int fderr_eof
= 0; /* EOF encountered readung from fderr. */
102 static int fdin_is_tty
= 0; /* fdin points to a tty. */
103 static int connection_in
; /* Connection to client (input). */
104 static int connection_out
; /* Connection to client (output). */
105 static int connection_closed
= 0; /* Connection to client closed. */
106 static u_int buffer_high
; /* "Soft" max buffer size. */
107 static int client_alive_timeouts
= 0;
110 * This SIGCHLD kludge is used to detect when the child exits. The server
111 * will exit after that, as soon as forwarded connections have terminated.
114 static volatile sig_atomic_t child_terminated
= 0; /* The child has terminated. */
116 /* Cleanup on signals (!use_privsep case only) */
117 static volatile sig_atomic_t received_sigterm
= 0;
120 static void server_init_dispatch(void);
123 * we write to this pipe if a SIGCHLD is caught in order to avoid
124 * the race between select() and child_terminated
126 static int notify_pipe
[2];
130 if (pipe(notify_pipe
) < 0) {
131 error("pipe(notify_pipe) failed %s", strerror(errno
));
132 } else if ((fcntl(notify_pipe
[0], F_SETFD
, 1) == -1) ||
133 (fcntl(notify_pipe
[1], F_SETFD
, 1) == -1)) {
134 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno
));
135 close(notify_pipe
[0]);
136 close(notify_pipe
[1]);
138 set_nonblock(notify_pipe
[0]);
139 set_nonblock(notify_pipe
[1]);
142 notify_pipe
[0] = -1; /* read end */
143 notify_pipe
[1] = -1; /* write end */
148 if (notify_pipe
[1] != -1)
149 write(notify_pipe
[1], "", 1);
152 notify_prepare(fd_set
*readset
)
154 if (notify_pipe
[0] != -1)
155 FD_SET(notify_pipe
[0], readset
);
158 notify_done(fd_set
*readset
)
162 if (notify_pipe
[0] != -1 && FD_ISSET(notify_pipe
[0], readset
))
163 while (read(notify_pipe
[0], &c
, 1) != -1)
164 debug2("notify_done: reading");
169 sigchld_handler(int sig
)
171 int save_errno
= errno
;
172 child_terminated
= 1;
174 mysignal(SIGCHLD
, sigchld_handler
);
182 sigterm_handler(int sig
)
184 received_sigterm
= sig
;
188 * Make packets from buffered stderr data, and buffer it for sending
192 make_packets_from_stderr_data(void)
196 /* Send buffered stderr data to the client. */
197 while (buffer_len(&stderr_buffer
) > 0 &&
198 packet_not_very_much_data_to_write()) {
199 len
= buffer_len(&stderr_buffer
);
200 if (packet_is_interactive()) {
204 /* Keep the packets at reasonable size. */
205 if (len
> packet_get_maxsize())
206 len
= packet_get_maxsize();
208 packet_start(SSH_SMSG_STDERR_DATA
);
209 packet_put_string(buffer_ptr(&stderr_buffer
), len
);
211 buffer_consume(&stderr_buffer
, len
);
217 * Make packets from buffered stdout data, and buffer it for sending to the
221 make_packets_from_stdout_data(void)
225 /* Send buffered stdout data to the client. */
226 while (buffer_len(&stdout_buffer
) > 0 &&
227 packet_not_very_much_data_to_write()) {
228 len
= buffer_len(&stdout_buffer
);
229 if (packet_is_interactive()) {
233 /* Keep the packets at reasonable size. */
234 if (len
> packet_get_maxsize())
235 len
= packet_get_maxsize();
237 packet_start(SSH_SMSG_STDOUT_DATA
);
238 packet_put_string(buffer_ptr(&stdout_buffer
), len
);
240 buffer_consume(&stdout_buffer
, len
);
246 client_alive_check(void)
250 /* timeout, check to see how many we have had */
251 if (++client_alive_timeouts
> options
.client_alive_count_max
) {
252 logit("Timeout, client not responding.");
257 * send a bogus global/channel request with "wantreply",
258 * we should get back a failure
260 if ((channel_id
= channel_find_open()) == -1) {
261 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
262 packet_put_cstring("keepalive@openssh.com");
263 packet_put_char(1); /* boolean: want reply */
265 channel_request_start(channel_id
, "keepalive@openssh.com", 1);
271 * Sleep in select() until we can do something. This will initialize the
272 * select masks. Upon return, the masks will indicate which descriptors
273 * have data or can accept data. Optionally, a maximum time can be specified
274 * for the duration of the wait (0 = infinite).
277 wait_until_can_do_something(fd_set
**readsetp
, fd_set
**writesetp
, int *maxfdp
,
278 u_int
*nallocp
, u_int max_time_milliseconds
)
280 struct timeval tv
, *tvp
;
282 int client_alive_scheduled
= 0;
285 * if using client_alive, set the max timeout accordingly,
286 * and indicate that this particular timeout was for client
287 * alive by setting the client_alive_scheduled flag.
289 * this could be randomized somewhat to make traffic
290 * analysis more difficult, but we're not doing it yet.
293 max_time_milliseconds
== 0 && options
.client_alive_interval
) {
294 client_alive_scheduled
= 1;
295 max_time_milliseconds
= options
.client_alive_interval
* 1000;
298 /* Allocate and update select() masks for channel descriptors. */
299 channel_prepare_select(readsetp
, writesetp
, maxfdp
, nallocp
, 0);
303 /* wrong: bad condition XXX */
304 if (channel_not_very_much_buffered_data())
306 FD_SET(connection_in
, *readsetp
);
309 * Read packets from the client unless we have too much
310 * buffered stdin or channel data.
312 if (buffer_len(&stdin_buffer
) < buffer_high
&&
313 channel_not_very_much_buffered_data())
314 FD_SET(connection_in
, *readsetp
);
316 * If there is not too much data already buffered going to
317 * the client, try to get some more data from the program.
319 if (packet_not_very_much_data_to_write()) {
321 FD_SET(fdout
, *readsetp
);
323 FD_SET(fderr
, *readsetp
);
326 * If we have buffered data, try to write some of that data
329 if (fdin
!= -1 && buffer_len(&stdin_buffer
) > 0)
330 FD_SET(fdin
, *writesetp
);
332 notify_prepare(*readsetp
);
335 * If we have buffered packet data going to the client, mark that
338 if (packet_have_data_to_write())
339 FD_SET(connection_out
, *writesetp
);
342 * If child has terminated and there is enough buffer space to read
343 * from it, then read as much as is available and exit.
345 if (child_terminated
&& packet_not_very_much_data_to_write())
346 if (max_time_milliseconds
== 0 || client_alive_scheduled
)
347 max_time_milliseconds
= 100;
349 if (max_time_milliseconds
== 0)
352 tv
.tv_sec
= max_time_milliseconds
/ 1000;
353 tv
.tv_usec
= 1000 * (max_time_milliseconds
% 1000);
357 /* Wait for something to happen, or the timeout to expire. */
358 ret
= select((*maxfdp
)+1, *readsetp
, *writesetp
, NULL
, tvp
);
361 memset(*readsetp
, 0, *nallocp
);
362 memset(*writesetp
, 0, *nallocp
);
364 error("select: %.100s", strerror(errno
));
365 } else if (ret
== 0 && client_alive_scheduled
)
366 client_alive_check();
368 notify_done(*readsetp
);
372 * Processes input from the client and the program. Input data is stored
373 * in buffers and processed later.
376 process_input(fd_set
*readset
)
381 /* Read and buffer any input data from the client. */
382 if (FD_ISSET(connection_in
, readset
)) {
383 len
= read(connection_in
, buf
, sizeof(buf
));
385 verbose("Connection closed by %.100s",
386 get_remote_ipaddr());
387 connection_closed
= 1;
391 } else if (len
< 0) {
392 if (errno
!= EINTR
&& errno
!= EAGAIN
) {
393 verbose("Read error from remote host "
395 get_remote_ipaddr(), strerror(errno
));
399 /* Buffer any received data. */
400 packet_process_incoming(buf
, len
);
406 /* Read and buffer any available stdout data from the program. */
407 if (!fdout_eof
&& FD_ISSET(fdout
, readset
)) {
409 len
= read(fdout
, buf
, sizeof(buf
));
410 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
413 } else if (len
<= 0) {
415 } else if ((!isatty(fdout
) && len
<= 0) ||
416 (isatty(fdout
) && (len
< 0 || (len
== 0 && errno
!= 0)))) {
420 buffer_append(&stdout_buffer
, buf
, len
);
424 /* Read and buffer any available stderr data from the program. */
425 if (!fderr_eof
&& FD_ISSET(fderr
, readset
)) {
427 len
= read(fderr
, buf
, sizeof(buf
));
428 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
431 } else if (len
<= 0) {
433 } else if ((!isatty(fderr
) && len
<= 0) ||
434 (isatty(fderr
) && (len
< 0 || (len
== 0 && errno
!= 0)))) {
438 buffer_append(&stderr_buffer
, buf
, len
);
444 * Sends data from internal buffers to client program stdin.
447 process_output(fd_set
*writeset
)
454 /* Write buffered data to program stdin. */
455 if (!compat20
&& fdin
!= -1 && FD_ISSET(fdin
, writeset
)) {
456 data
= buffer_ptr(&stdin_buffer
);
457 dlen
= buffer_len(&stdin_buffer
);
458 len
= write(fdin
, data
, dlen
);
459 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
461 } else if (len
<= 0) {
465 shutdown(fdin
, SHUT_WR
); /* We will no longer send. */
468 /* Successful write. */
469 if (fdin_is_tty
&& dlen
>= 1 && data
[0] != '\r' &&
470 tcgetattr(fdin
, &tio
) == 0 &&
471 !(tio
.c_lflag
& ECHO
) && (tio
.c_lflag
& ICANON
)) {
473 * Simulate echo to reduce the impact of
476 packet_send_ignore(len
);
479 /* Consume the data from the buffer. */
480 buffer_consume(&stdin_buffer
, len
);
481 /* Update the count of bytes written to the program. */
485 /* Send any buffered packet data to the client. */
486 if (FD_ISSET(connection_out
, writeset
))
491 * Wait until all buffered output has been sent to the client.
492 * This is used when the program terminates.
497 /* Send any buffered stdout data to the client. */
498 if (buffer_len(&stdout_buffer
) > 0) {
499 packet_start(SSH_SMSG_STDOUT_DATA
);
500 packet_put_string(buffer_ptr(&stdout_buffer
),
501 buffer_len(&stdout_buffer
));
503 /* Update the count of sent bytes. */
504 stdout_bytes
+= buffer_len(&stdout_buffer
);
506 /* Send any buffered stderr data to the client. */
507 if (buffer_len(&stderr_buffer
) > 0) {
508 packet_start(SSH_SMSG_STDERR_DATA
);
509 packet_put_string(buffer_ptr(&stderr_buffer
),
510 buffer_len(&stderr_buffer
));
512 /* Update the count of sent bytes. */
513 stderr_bytes
+= buffer_len(&stderr_buffer
);
515 /* Wait until all buffered data has been written to the client. */
520 process_buffered_input_packets(void)
522 dispatch_run(DISPATCH_NONBLOCK
, NULL
, compat20
? xxx_kex
: NULL
);
526 * Performs the interactive session. This handles data transmission between
527 * the client and the program. Note that the notion of stdin, stdout, and
528 * stderr in this function is sort of reversed: this function writes to
529 * stdin (of the child program), and reads from stdout and stderr (of the
533 server_loop(pid_t pid
, int fdin_arg
, int fdout_arg
, int fderr_arg
)
535 fd_set
*readset
= NULL
, *writeset
= NULL
;
538 int wait_status
; /* Status returned by wait(). */
539 pid_t wait_pid
; /* pid returned by wait(). */
540 int waiting_termination
= 0; /* Have displayed waiting close message. */
541 u_int max_time_milliseconds
;
542 u_int previous_stdout_buffer_bytes
;
543 u_int stdout_buffer_bytes
;
546 debug("Entering interactive session.");
548 /* Initialize the SIGCHLD kludge. */
549 child_terminated
= 0;
550 mysignal(SIGCHLD
, sigchld_handler
);
553 signal(SIGTERM
, sigterm_handler
);
554 signal(SIGINT
, sigterm_handler
);
555 signal(SIGQUIT
, sigterm_handler
);
558 /* Initialize our global variables. */
566 /* we don't have stderr for interactive terminal sessions, see below */
570 if (!(datafellows
& SSH_BUG_IGNOREMSG
) && isatty(fdin
))
573 connection_in
= packet_get_connection_in();
574 connection_out
= packet_get_connection_out();
578 previous_stdout_buffer_bytes
= 0;
580 /* Set approximate I/O buffer size. */
581 if (packet_is_interactive())
584 buffer_high
= 64 * 1024;
587 /* Initialize max_fd to the maximum of the known file descriptors. */
588 max_fd
= MAX(connection_in
, connection_out
);
589 max_fd
= MAX(max_fd
, fdin
);
590 max_fd
= MAX(max_fd
, fdout
);
592 max_fd
= MAX(max_fd
, fderr
);
595 /* Initialize Initialize buffers. */
596 buffer_init(&stdin_buffer
);
597 buffer_init(&stdout_buffer
);
598 buffer_init(&stderr_buffer
);
601 * If we have no separate fderr (which is the case when we have a pty
602 * - there we cannot make difference between data sent to stdout and
603 * stderr), indicate that we have seen an EOF from stderr. This way
604 * we don't need to check the descriptor everywhere.
609 server_init_dispatch();
611 /* Main loop of the server for the interactive session mode. */
614 /* Process buffered packets from the client. */
615 process_buffered_input_packets();
618 * If we have received eof, and there is no more pending
619 * input data, cause a real eof by closing fdin.
621 if (stdin_eof
&& fdin
!= -1 && buffer_len(&stdin_buffer
) == 0) {
625 shutdown(fdin
, SHUT_WR
); /* We will no longer send. */
628 /* Make packets from buffered stderr data to send to the client. */
629 make_packets_from_stderr_data();
632 * Make packets from buffered stdout data to send to the
633 * client. If there is very little to send, this arranges to
634 * not send them now, but to wait a short while to see if we
635 * are getting more data. This is necessary, as some systems
636 * wake up readers from a pty after each separate character.
638 max_time_milliseconds
= 0;
639 stdout_buffer_bytes
= buffer_len(&stdout_buffer
);
640 if (stdout_buffer_bytes
!= 0 && stdout_buffer_bytes
< 256 &&
641 stdout_buffer_bytes
!= previous_stdout_buffer_bytes
) {
642 /* try again after a while */
643 max_time_milliseconds
= 10;
646 make_packets_from_stdout_data();
648 previous_stdout_buffer_bytes
= buffer_len(&stdout_buffer
);
650 /* Send channel data to the client. */
651 if (packet_not_very_much_data_to_write())
652 channel_output_poll();
655 * Bail out of the loop if the program has closed its output
656 * descriptors, and we have no more data to send to the
657 * client, and there is no pending buffered data.
659 if (fdout_eof
&& fderr_eof
&& !packet_have_data_to_write() &&
660 buffer_len(&stdout_buffer
) == 0 && buffer_len(&stderr_buffer
) == 0) {
661 if (!channel_still_open())
663 if (!waiting_termination
) {
664 const char *s
= "Waiting for forwarded connections to terminate...\r\n";
666 waiting_termination
= 1;
667 buffer_append(&stderr_buffer
, s
, strlen(s
));
669 /* Display list of open channels. */
670 cp
= channel_open_message();
671 buffer_append(&stderr_buffer
, cp
, strlen(cp
));
675 max_fd
= MAX(connection_in
, connection_out
);
676 max_fd
= MAX(max_fd
, fdin
);
677 max_fd
= MAX(max_fd
, fdout
);
678 max_fd
= MAX(max_fd
, fderr
);
679 max_fd
= MAX(max_fd
, notify_pipe
[0]);
681 /* Sleep in select() until we can do something. */
682 wait_until_can_do_something(&readset
, &writeset
, &max_fd
,
683 &nalloc
, max_time_milliseconds
);
685 if (received_sigterm
) {
686 logit("Exiting on signal %d", received_sigterm
);
687 /* Clean up sessions, utmp, etc. */
691 /* Process any channel events. */
692 channel_after_select(readset
, writeset
);
694 /* Process input from the client and from program stdout/stderr. */
695 process_input(readset
);
697 /* Process output to the client and to program stdin. */
698 process_output(writeset
);
705 /* Cleanup and termination code. */
707 /* Wait until all output has been sent to the client. */
710 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
711 stdin_bytes
, fdout_bytes
, stdout_bytes
, stderr_bytes
);
713 /* Free and clear the buffers. */
714 buffer_free(&stdin_buffer
);
715 buffer_free(&stdout_buffer
);
716 buffer_free(&stderr_buffer
);
718 /* Close the file descriptors. */
733 /* We no longer want our SIGCHLD handler to be called. */
734 mysignal(SIGCHLD
, SIG_DFL
);
736 while ((wait_pid
= waitpid(-1, &wait_status
, 0)) < 0)
738 packet_disconnect("wait: %.100s", strerror(errno
));
740 error("Strange, wait returned pid %ld, expected %ld",
741 (long)wait_pid
, (long)pid
);
743 /* Check if it exited normally. */
744 if (WIFEXITED(wait_status
)) {
745 /* Yes, normal exit. Get exit status and send it to the client. */
746 debug("Command exited with status %d.", WEXITSTATUS(wait_status
));
747 packet_start(SSH_SMSG_EXITSTATUS
);
748 packet_put_int(WEXITSTATUS(wait_status
));
753 * Wait for exit confirmation. Note that there might be
754 * other packets coming before it; however, the program has
755 * already died so we just ignore them. The client is
756 * supposed to respond with the confirmation when it receives
760 type
= packet_read();
762 while (type
!= SSH_CMSG_EXIT_CONFIRMATION
);
764 debug("Received exit confirmation.");
767 /* Check if the program terminated due to a signal. */
768 if (WIFSIGNALED(wait_status
))
769 packet_disconnect("Command terminated on signal %d.",
770 WTERMSIG(wait_status
));
772 /* Some weird exit cause. Just exit. */
773 packet_disconnect("wait returned status %04x.", wait_status
);
778 collect_children(void)
784 /* block SIGCHLD while we check for dead children */
786 sigaddset(&nset
, SIGCHLD
);
787 sigprocmask(SIG_BLOCK
, &nset
, &oset
);
788 if (child_terminated
) {
789 debug("Received SIGCHLD.");
790 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0 ||
791 (pid
< 0 && errno
== EINTR
))
793 session_close_by_pid(pid
, status
);
794 child_terminated
= 0;
796 sigprocmask(SIG_SETMASK
, &oset
, NULL
);
800 server_loop2(Authctxt
*authctxt
)
802 fd_set
*readset
= NULL
, *writeset
= NULL
;
803 int rekeying
= 0, max_fd
, nalloc
= 0;
805 debug("Entering interactive session for SSH2.");
807 mysignal(SIGCHLD
, sigchld_handler
);
808 child_terminated
= 0;
809 connection_in
= packet_get_connection_in();
810 connection_out
= packet_get_connection_out();
813 signal(SIGTERM
, sigterm_handler
);
814 signal(SIGINT
, sigterm_handler
);
815 signal(SIGQUIT
, sigterm_handler
);
820 max_fd
= MAX(connection_in
, connection_out
);
821 max_fd
= MAX(max_fd
, notify_pipe
[0]);
823 server_init_dispatch();
826 process_buffered_input_packets();
828 rekeying
= (xxx_kex
!= NULL
&& !xxx_kex
->done
);
830 if (!rekeying
&& packet_not_very_much_data_to_write())
831 channel_output_poll();
832 wait_until_can_do_something(&readset
, &writeset
, &max_fd
,
835 if (received_sigterm
) {
836 logit("Exiting on signal %d", received_sigterm
);
837 /* Clean up sessions, utmp, etc. */
843 channel_after_select(readset
, writeset
);
844 if (packet_need_rekeying()) {
845 debug("need rekeying");
847 kex_send_kexinit(xxx_kex
);
850 process_input(readset
);
851 if (connection_closed
)
853 process_output(writeset
);
862 /* free all channels, no more reads and writes */
865 /* free remaining sessions, e.g. remove wtmp entries */
866 session_destroy_all(NULL
);
870 server_input_keep_alive(int type
, u_int32_t seq
, void *ctxt
)
872 debug("Got %d/%u for keepalive", type
, seq
);
874 * reset timeout, since we got a sane answer from the client.
875 * even if this was generated by something other than
876 * the bogus CHANNEL_REQUEST we send for keepalives.
878 client_alive_timeouts
= 0;
882 server_input_stdin_data(int type
, u_int32_t seq
, void *ctxt
)
887 /* Stdin data from the client. Append it to the buffer. */
888 /* Ignore any data if the client has closed stdin. */
891 data
= packet_get_string(&data_len
);
893 buffer_append(&stdin_buffer
, data
, data_len
);
894 memset(data
, 0, data_len
);
899 server_input_eof(int type
, u_int32_t seq
, void *ctxt
)
902 * Eof from the client. The stdin descriptor to the
903 * program will be closed when all buffered data has
906 debug("EOF received for stdin.");
912 server_input_window_size(int type
, u_int32_t seq
, void *ctxt
)
914 u_int row
= packet_get_int();
915 u_int col
= packet_get_int();
916 u_int xpixel
= packet_get_int();
917 u_int ypixel
= packet_get_int();
919 debug("Window change received.");
922 pty_change_window_size(fdin
, row
, col
, xpixel
, ypixel
);
926 server_request_direct_tcpip(void)
930 char *target
, *originator
;
931 int target_port
, originator_port
;
933 target
= packet_get_string(NULL
);
934 target_port
= packet_get_int();
935 originator
= packet_get_string(NULL
);
936 originator_port
= packet_get_int();
939 debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
940 originator
, originator_port
, target
, target_port
);
942 /* XXX check permission */
943 sock
= channel_connect_to(target
, target_port
);
948 c
= channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING
,
949 sock
, sock
, -1, CHAN_TCP_WINDOW_DEFAULT
,
950 CHAN_TCP_PACKET_DEFAULT
, 0, "direct-tcpip", 1);
955 server_request_tun(void)
961 mode
= packet_get_int();
963 case SSH_TUNMODE_POINTOPOINT
:
964 case SSH_TUNMODE_ETHERNET
:
967 packet_send_debug("Unsupported tunnel device mode.");
970 if ((options
.permit_tun
& mode
) == 0) {
971 packet_send_debug("Server has rejected tunnel device "
976 tun
= packet_get_int();
977 if (forced_tun_device
!= -1) {
978 if (tun
!= SSH_TUNID_ANY
&& forced_tun_device
!= tun
)
980 tun
= forced_tun_device
;
982 sock
= tun_open(tun
, mode
);
985 c
= channel_new("tun", SSH_CHANNEL_OPEN
, sock
, sock
, -1,
986 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
, 0, "tun", 1);
988 #if defined(SSH_TUN_FILTER)
989 if (mode
== SSH_TUNMODE_POINTOPOINT
)
990 channel_register_filter(c
->self
, sys_tun_infilter
,
996 packet_send_debug("Failed to open the tunnel device.");
1001 server_request_session(void)
1005 debug("input_session_request");
1008 * A server session has no fd to read or write until a
1009 * CHANNEL_REQUEST for a shell is made, so we set the type to
1010 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
1011 * CHANNEL_REQUEST messages is registered.
1013 c
= channel_new("session", SSH_CHANNEL_LARVAL
,
1014 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT
,
1015 0, "server-session", 1);
1016 if (session_open(the_authctxt
, c
->self
) != 1) {
1017 debug("session open failed, free channel %d", c
->self
);
1021 channel_register_cleanup(c
->self
, session_close_by_channel
, 0);
1026 server_input_channel_open(int type
, u_int32_t seq
, void *ctxt
)
1031 u_int rmaxpack
, rwindow
, len
;
1033 ctype
= packet_get_string(&len
);
1034 rchan
= packet_get_int();
1035 rwindow
= packet_get_int();
1036 rmaxpack
= packet_get_int();
1038 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1039 ctype
, rchan
, rwindow
, rmaxpack
);
1041 if (strcmp(ctype
, "session") == 0) {
1042 c
= server_request_session();
1043 } else if (strcmp(ctype
, "direct-tcpip") == 0) {
1044 c
= server_request_direct_tcpip();
1045 } else if (strcmp(ctype
, "tun@openssh.com") == 0) {
1046 c
= server_request_tun();
1049 debug("server_input_channel_open: confirm %s", ctype
);
1050 c
->remote_id
= rchan
;
1051 c
->remote_window
= rwindow
;
1052 c
->remote_maxpacket
= rmaxpack
;
1053 if (c
->type
!= SSH_CHANNEL_CONNECTING
) {
1054 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
1055 packet_put_int(c
->remote_id
);
1056 packet_put_int(c
->self
);
1057 packet_put_int(c
->local_window
);
1058 packet_put_int(c
->local_maxpacket
);
1062 debug("server_input_channel_open: failure %s", ctype
);
1063 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
1064 packet_put_int(rchan
);
1065 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
);
1066 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
1067 packet_put_cstring("open failed");
1068 packet_put_cstring("");
1076 server_input_global_request(int type
, u_int32_t seq
, void *ctxt
)
1082 rtype
= packet_get_string(NULL
);
1083 want_reply
= packet_get_char();
1084 debug("server_input_global_request: rtype %s want_reply %d", rtype
, want_reply
);
1086 /* -R style forwarding */
1087 if (strcmp(rtype
, "tcpip-forward") == 0) {
1089 char *listen_address
;
1090 u_short listen_port
;
1092 pw
= the_authctxt
->pw
;
1093 if (pw
== NULL
|| !the_authctxt
->valid
)
1094 fatal("server_input_global_request: no/invalid user");
1095 listen_address
= packet_get_string(NULL
);
1096 listen_port
= (u_short
)packet_get_int();
1097 debug("server_input_global_request: tcpip-forward listen %s port %d",
1098 listen_address
, listen_port
);
1100 /* check permissions */
1101 if (!options
.allow_tcp_forwarding
||
1102 no_port_forwarding_flag
1103 #ifndef NO_IPPORT_RESERVED_CONCEPT
1104 || (listen_port
< IPPORT_RESERVED
&& pw
->pw_uid
!= 0)
1108 packet_send_debug("Server has disabled port forwarding.");
1110 /* Start listening on the port */
1111 success
= channel_setup_remote_fwd_listener(
1112 listen_address
, listen_port
, options
.gateway_ports
);
1114 xfree(listen_address
);
1115 } else if (strcmp(rtype
, "cancel-tcpip-forward") == 0) {
1116 char *cancel_address
;
1117 u_short cancel_port
;
1119 cancel_address
= packet_get_string(NULL
);
1120 cancel_port
= (u_short
)packet_get_int();
1121 debug("%s: cancel-tcpip-forward addr %s port %d", __func__
,
1122 cancel_address
, cancel_port
);
1124 success
= channel_cancel_rport_listener(cancel_address
,
1126 xfree(cancel_address
);
1129 packet_start(success
?
1130 SSH2_MSG_REQUEST_SUCCESS
: SSH2_MSG_REQUEST_FAILURE
);
1132 packet_write_wait();
1138 server_input_channel_req(int type
, u_int32_t seq
, void *ctxt
)
1141 int id
, reply
, success
= 0;
1144 id
= packet_get_int();
1145 rtype
= packet_get_string(NULL
);
1146 reply
= packet_get_char();
1148 debug("server_input_channel_req: channel %d request %s reply %d",
1151 if ((c
= channel_lookup(id
)) == NULL
)
1152 packet_disconnect("server_input_channel_req: "
1153 "unknown channel %d", id
);
1154 if (c
->type
== SSH_CHANNEL_LARVAL
|| c
->type
== SSH_CHANNEL_OPEN
)
1155 success
= session_input_channel_req(c
, rtype
);
1157 packet_start(success
?
1158 SSH2_MSG_CHANNEL_SUCCESS
: SSH2_MSG_CHANNEL_FAILURE
);
1159 packet_put_int(c
->remote_id
);
1166 server_init_dispatch_20(void)
1168 debug("server_init_dispatch_20");
1169 dispatch_init(&dispatch_protocol_error
);
1170 dispatch_set(SSH2_MSG_CHANNEL_CLOSE
, &channel_input_oclose
);
1171 dispatch_set(SSH2_MSG_CHANNEL_DATA
, &channel_input_data
);
1172 dispatch_set(SSH2_MSG_CHANNEL_EOF
, &channel_input_ieof
);
1173 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA
, &channel_input_extended_data
);
1174 dispatch_set(SSH2_MSG_CHANNEL_OPEN
, &server_input_channel_open
);
1175 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
1176 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
1177 dispatch_set(SSH2_MSG_CHANNEL_REQUEST
, &server_input_channel_req
);
1178 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST
, &channel_input_window_adjust
);
1179 dispatch_set(SSH2_MSG_GLOBAL_REQUEST
, &server_input_global_request
);
1181 dispatch_set(SSH2_MSG_CHANNEL_FAILURE
, &server_input_keep_alive
);
1182 dispatch_set(SSH2_MSG_REQUEST_SUCCESS
, &server_input_keep_alive
);
1183 dispatch_set(SSH2_MSG_REQUEST_FAILURE
, &server_input_keep_alive
);
1185 dispatch_set(SSH2_MSG_KEXINIT
, &kex_input_kexinit
);
1188 server_init_dispatch_13(void)
1190 debug("server_init_dispatch_13");
1191 dispatch_init(NULL
);
1192 dispatch_set(SSH_CMSG_EOF
, &server_input_eof
);
1193 dispatch_set(SSH_CMSG_STDIN_DATA
, &server_input_stdin_data
);
1194 dispatch_set(SSH_CMSG_WINDOW_SIZE
, &server_input_window_size
);
1195 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_close
);
1196 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, &channel_input_close_confirmation
);
1197 dispatch_set(SSH_MSG_CHANNEL_DATA
, &channel_input_data
);
1198 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
1199 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
1200 dispatch_set(SSH_MSG_PORT_OPEN
, &channel_input_port_open
);
1203 server_init_dispatch_15(void)
1205 server_init_dispatch_13();
1206 debug("server_init_dispatch_15");
1207 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_ieof
);
1208 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, &channel_input_oclose
);
1211 server_init_dispatch(void)
1214 server_init_dispatch_20();
1216 server_init_dispatch_13();
1218 server_init_dispatch_15();