1 /* $OpenBSD: serverloop.c,v 1.138 2006/07/09 15:15:11 stevesk 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>
42 #include <sys/socket.h>
44 #include <netinet/in.h>
65 #include "auth-options.h"
66 #include "serverloop.h"
70 extern ServerOptions options
;
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;
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];
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]);
127 set_nonblock(notify_pipe
[0]);
128 set_nonblock(notify_pipe
[1]);
131 notify_pipe
[0] = -1; /* read end */
132 notify_pipe
[1] = -1; /* write end */
137 if (notify_pipe
[1] != -1)
138 write(notify_pipe
[1], "", 1);
141 notify_prepare(fd_set
*readset
)
143 if (notify_pipe
[0] != -1)
144 FD_SET(notify_pipe
[0], readset
);
147 notify_done(fd_set
*readset
)
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");
158 sigchld_handler(int sig
)
160 int save_errno
= errno
;
161 child_terminated
= 1;
163 mysignal(SIGCHLD
, sigchld_handler
);
171 sigterm_handler(int sig
)
173 received_sigterm
= sig
;
177 * Make packets from buffered stderr data, and buffer it for sending
181 make_packets_from_stderr_data(void)
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()) {
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
);
200 buffer_consume(&stderr_buffer
, len
);
206 * Make packets from buffered stdout data, and buffer it for sending to the
210 make_packets_from_stdout_data(void)
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()) {
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
);
229 buffer_consume(&stdout_buffer
, len
);
235 client_alive_check(void)
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 */
252 channel_request_start(channel_id
, "keepalive@openssh.com", 1);
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).
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
;
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.
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);
290 /* wrong: bad condition XXX */
291 if (channel_not_very_much_buffered_data())
293 FD_SET(connection_in
, *readsetp
);
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()) {
308 FD_SET(fdout
, *readsetp
);
310 FD_SET(fderr
, *readsetp
);
313 * If we have buffered data, try to write some of that data
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
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)
339 tv
.tv_sec
= max_time_milliseconds
/ 1000;
340 tv
.tv_usec
= 1000 * (max_time_milliseconds
% 1000);
344 /* Wait for something to happen, or the timeout to expire. */
345 ret
= select((*maxfdp
)+1, *readsetp
, *writesetp
, NULL
, tvp
);
348 memset(*readsetp
, 0, *nallocp
);
349 memset(*writesetp
, 0, *nallocp
);
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.
363 process_input(fd_set
*readset
)
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
));
372 verbose("Connection closed by %.100s",
373 get_remote_ipaddr());
374 connection_closed
= 1;
378 } else if (len
< 0) {
379 if (errno
!= EINTR
&& errno
!= EAGAIN
) {
380 verbose("Read error from remote host "
382 get_remote_ipaddr(), strerror(errno
));
386 /* Buffer any received data. */
387 packet_process_incoming(buf
, len
);
393 /* Read and buffer any available stdout data from the program. */
394 if (!fdout_eof
&& FD_ISSET(fdout
, readset
)) {
396 len
= read(fdout
, buf
, sizeof(buf
));
397 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
400 } else if (len
<= 0) {
402 } else if ((!isatty(fdout
) && len
<= 0) ||
403 (isatty(fdout
) && (len
< 0 || (len
== 0 && errno
!= 0)))) {
407 buffer_append(&stdout_buffer
, buf
, len
);
411 /* Read and buffer any available stderr data from the program. */
412 if (!fderr_eof
&& FD_ISSET(fderr
, readset
)) {
414 len
= read(fderr
, buf
, sizeof(buf
));
415 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
418 } else if (len
<= 0) {
420 } else if ((!isatty(fderr
) && len
<= 0) ||
421 (isatty(fderr
) && (len
< 0 || (len
== 0 && errno
!= 0)))) {
425 buffer_append(&stderr_buffer
, buf
, len
);
431 * Sends data from internal buffers to client program stdin.
434 process_output(fd_set
*writeset
)
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
)) {
448 } else if (len
<= 0) {
452 shutdown(fdin
, SHUT_WR
); /* We will no longer send. */
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
463 packet_send_ignore(len
);
466 /* Consume the data from the buffer. */
467 buffer_consume(&stdin_buffer
, len
);
468 /* Update the count of bytes written to the program. */
472 /* Send any buffered packet data to the client. */
473 if (FD_ISSET(connection_out
, writeset
))
478 * Wait until all buffered output has been sent to the client.
479 * This is used when the program terminates.
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
));
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
));
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. */
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
520 server_loop(pid_t pid
, int fdin_arg
, int fdout_arg
, int fderr_arg
)
522 fd_set
*readset
= NULL
, *writeset
= NULL
;
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
;
533 debug("Entering interactive session.");
535 /* Initialize the SIGCHLD kludge. */
536 child_terminated
= 0;
537 mysignal(SIGCHLD
, sigchld_handler
);
540 signal(SIGTERM
, sigterm_handler
);
541 signal(SIGINT
, sigterm_handler
);
542 signal(SIGQUIT
, sigterm_handler
);
545 /* Initialize our global variables. */
553 /* we don't have stderr for interactive terminal sessions, see below */
557 if (!(datafellows
& SSH_BUG_IGNOREMSG
) && isatty(fdin
))
560 connection_in
= packet_get_connection_in();
561 connection_out
= packet_get_connection_out();
565 previous_stdout_buffer_bytes
= 0;
567 /* Set approximate I/O buffer size. */
568 if (packet_is_interactive())
571 buffer_high
= 64 * 1024;
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
);
579 max_fd
= MAX(max_fd
, fderr
);
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.
596 server_init_dispatch();
598 /* Main loop of the server for the interactive session mode. */
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) {
612 shutdown(fdin
, SHUT_WR
); /* We will no longer send. */
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;
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())
650 if (!waiting_termination
) {
651 const char *s
= "Waiting for forwarded connections to terminate...\r\n";
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
));
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. */
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
);
692 /* Cleanup and termination code. */
694 /* Wait until all output has been sent to the client. */
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. */
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)
725 packet_disconnect("wait: %.100s", strerror(errno
));
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
));
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
747 type
= packet_read();
749 while (type
!= SSH_CMSG_EXIT_CONFIRMATION
);
751 debug("Received exit confirmation.");
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
);
765 collect_children(void)
771 /* block SIGCHLD while we check for dead children */
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
))
780 session_close_by_pid(pid
, status
);
781 child_terminated
= 0;
783 sigprocmask(SIG_SETMASK
, &oset
, NULL
);
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();
800 signal(SIGTERM
, sigterm_handler
);
801 signal(SIGINT
, sigterm_handler
);
802 signal(SIGQUIT
, sigterm_handler
);
807 max_fd
= MAX(connection_in
, connection_out
);
808 max_fd
= MAX(max_fd
, notify_pipe
[0]);
810 server_init_dispatch();
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
,
822 if (received_sigterm
) {
823 logit("Exiting on signal %d", received_sigterm
);
824 /* Clean up sessions, utmp, etc. */
830 channel_after_select(readset
, writeset
);
831 if (packet_need_rekeying()) {
832 debug("need rekeying");
834 kex_send_kexinit(xxx_kex
);
837 process_input(readset
);
838 if (connection_closed
)
840 process_output(writeset
);
849 /* free all channels, no more reads and writes */
852 /* free remaining sessions, e.g. remove wtmp entries */
853 session_destroy_all(NULL
);
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;
869 server_input_stdin_data(int type
, u_int32_t seq
, void *ctxt
)
874 /* Stdin data from the client. Append it to the buffer. */
875 /* Ignore any data if the client has closed stdin. */
878 data
= packet_get_string(&data_len
);
880 buffer_append(&stdin_buffer
, data
, data_len
);
881 memset(data
, 0, data_len
);
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
893 debug("EOF received for stdin.");
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.");
909 pty_change_window_size(fdin
, row
, col
, xpixel
, ypixel
);
913 server_request_direct_tcpip(void)
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();
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
);
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);
942 server_request_tun(void)
948 mode
= packet_get_int();
950 case SSH_TUNMODE_POINTOPOINT
:
951 case SSH_TUNMODE_ETHERNET
:
954 packet_send_debug("Unsupported tunnel device mode.");
957 if ((options
.permit_tun
& mode
) == 0) {
958 packet_send_debug("Server has rejected tunnel device "
963 tun
= packet_get_int();
964 if (forced_tun_device
!= -1) {
965 if (tun
!= SSH_TUNID_ANY
&& forced_tun_device
!= tun
)
967 tun
= forced_tun_device
;
969 sock
= tun_open(tun
, mode
);
972 c
= channel_new("tun", SSH_CHANNEL_OPEN
, sock
, sock
, -1,
973 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
, 0, "tun", 1);
975 #if defined(SSH_TUN_FILTER)
976 if (mode
== SSH_TUNMODE_POINTOPOINT
)
977 channel_register_filter(c
->self
, sys_tun_infilter
,
983 packet_send_debug("Failed to open the tunnel device.");
988 server_request_session(void)
992 debug("input_session_request");
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
);
1008 channel_register_cleanup(c
->self
, session_close_by_channel
, 0);
1013 server_input_channel_open(int type
, u_int32_t seq
, void *ctxt
)
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();
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
);
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("");
1063 server_input_global_request(int type
, u_int32_t seq
, void *ctxt
)
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) {
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)
1095 packet_send_debug("Server has disabled port forwarding.");
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
,
1113 xfree(cancel_address
);
1116 packet_start(success
?
1117 SSH2_MSG_REQUEST_SUCCESS
: SSH2_MSG_REQUEST_FAILURE
);
1119 packet_write_wait();
1125 server_input_channel_req(int type
, u_int32_t seq
, void *ctxt
)
1128 int id
, reply
, success
= 0;
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",
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
);
1144 packet_start(success
?
1145 SSH2_MSG_CHANNEL_SUCCESS
: SSH2_MSG_CHANNEL_FAILURE
);
1146 packet_put_int(c
->remote_id
);
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
);
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
);
1172 dispatch_set(SSH2_MSG_KEXINIT
, &kex_input_kexinit
);
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
);
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
);
1198 server_init_dispatch(void)
1201 server_init_dispatch_20();
1203 server_init_dispatch_13();
1205 server_init_dispatch_15();