]> andersk Git - openssh.git/blame_incremental - serverloop.c
- stevesk@cvs.openbsd.org 2006/07/08 23:30:06
[openssh.git] / serverloop.c
... / ...
CommitLineData
1/* $OpenBSD: serverloop.c,v 1.137 2006/07/06 16:03:53 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.
7 *
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".
13 *
14 * SSH2 support by Markus Friedl.
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 *
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.
25 *
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.
36 */
37
38#include "includes.h"
39
40#include <sys/types.h>
41#include <sys/wait.h>
42#include <sys/socket.h>
43
44#include <netinet/in.h>
45
46#include <pwd.h>
47#include <signal.h>
48#include <termios.h>
49
50#include "xmalloc.h"
51#include "packet.h"
52#include "buffer.h"
53#include "log.h"
54#include "servconf.h"
55#include "canohost.h"
56#include "sshpty.h"
57#include "channels.h"
58#include "compat.h"
59#include "ssh1.h"
60#include "ssh2.h"
61#include "auth.h"
62#include "session.h"
63#include "dispatch.h"
64#include "auth-options.h"
65#include "serverloop.h"
66#include "misc.h"
67#include "kex.h"
68
69extern ServerOptions options;
70
71/* XXX */
72extern Kex *xxx_kex;
73extern Authctxt *the_authctxt;
74extern int use_privsep;
75
76static Buffer stdin_buffer; /* Buffer for stdin data. */
77static Buffer stdout_buffer; /* Buffer for stdout data. */
78static Buffer stderr_buffer; /* Buffer for stderr data. */
79static int fdin; /* Descriptor for stdin (for writing) */
80static int fdout; /* Descriptor for stdout (for reading);
81 May be same number as fdin. */
82static int fderr; /* Descriptor for stderr. May be -1. */
83static long stdin_bytes = 0; /* Number of bytes written to stdin. */
84static long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
85static long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
86static long fdout_bytes = 0; /* Number of stdout bytes read from program. */
87static int stdin_eof = 0; /* EOF message received from client. */
88static int fdout_eof = 0; /* EOF encountered reading from fdout. */
89static int fderr_eof = 0; /* EOF encountered readung from fderr. */
90static int fdin_is_tty = 0; /* fdin points to a tty. */
91static int connection_in; /* Connection to client (input). */
92static int connection_out; /* Connection to client (output). */
93static int connection_closed = 0; /* Connection to client closed. */
94static u_int buffer_high; /* "Soft" max buffer size. */
95static int client_alive_timeouts = 0;
96
97/*
98 * This SIGCHLD kludge is used to detect when the child exits. The server
99 * will exit after that, as soon as forwarded connections have terminated.
100 */
101
102static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */
103
104/* Cleanup on signals (!use_privsep case only) */
105static volatile sig_atomic_t received_sigterm = 0;
106
107/* prototypes */
108static void server_init_dispatch(void);
109
110/*
111 * we write to this pipe if a SIGCHLD is caught in order to avoid
112 * the race between select() and child_terminated
113 */
114static int notify_pipe[2];
115static void
116notify_setup(void)
117{
118 if (pipe(notify_pipe) < 0) {
119 error("pipe(notify_pipe) failed %s", strerror(errno));
120 } else if ((fcntl(notify_pipe[0], F_SETFD, 1) == -1) ||
121 (fcntl(notify_pipe[1], F_SETFD, 1) == -1)) {
122 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
123 close(notify_pipe[0]);
124 close(notify_pipe[1]);
125 } else {
126 set_nonblock(notify_pipe[0]);
127 set_nonblock(notify_pipe[1]);
128 return;
129 }
130 notify_pipe[0] = -1; /* read end */
131 notify_pipe[1] = -1; /* write end */
132}
133static void
134notify_parent(void)
135{
136 if (notify_pipe[1] != -1)
137 write(notify_pipe[1], "", 1);
138}
139static void
140notify_prepare(fd_set *readset)
141{
142 if (notify_pipe[0] != -1)
143 FD_SET(notify_pipe[0], readset);
144}
145static void
146notify_done(fd_set *readset)
147{
148 char c;
149
150 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
151 while (read(notify_pipe[0], &c, 1) != -1)
152 debug2("notify_done: reading");
153}
154
155/*ARGSUSED*/
156static void
157sigchld_handler(int sig)
158{
159 int save_errno = errno;
160 child_terminated = 1;
161#ifndef _UNICOS
162 mysignal(SIGCHLD, sigchld_handler);
163#endif
164 notify_parent();
165 errno = save_errno;
166}
167
168/*ARGSUSED*/
169static void
170sigterm_handler(int sig)
171{
172 received_sigterm = sig;
173}
174
175/*
176 * Make packets from buffered stderr data, and buffer it for sending
177 * to the client.
178 */
179static void
180make_packets_from_stderr_data(void)
181{
182 u_int len;
183
184 /* Send buffered stderr data to the client. */
185 while (buffer_len(&stderr_buffer) > 0 &&
186 packet_not_very_much_data_to_write()) {
187 len = buffer_len(&stderr_buffer);
188 if (packet_is_interactive()) {
189 if (len > 512)
190 len = 512;
191 } else {
192 /* Keep the packets at reasonable size. */
193 if (len > packet_get_maxsize())
194 len = packet_get_maxsize();
195 }
196 packet_start(SSH_SMSG_STDERR_DATA);
197 packet_put_string(buffer_ptr(&stderr_buffer), len);
198 packet_send();
199 buffer_consume(&stderr_buffer, len);
200 stderr_bytes += len;
201 }
202}
203
204/*
205 * Make packets from buffered stdout data, and buffer it for sending to the
206 * client.
207 */
208static void
209make_packets_from_stdout_data(void)
210{
211 u_int len;
212
213 /* Send buffered stdout data to the client. */
214 while (buffer_len(&stdout_buffer) > 0 &&
215 packet_not_very_much_data_to_write()) {
216 len = buffer_len(&stdout_buffer);
217 if (packet_is_interactive()) {
218 if (len > 512)
219 len = 512;
220 } else {
221 /* Keep the packets at reasonable size. */
222 if (len > packet_get_maxsize())
223 len = packet_get_maxsize();
224 }
225 packet_start(SSH_SMSG_STDOUT_DATA);
226 packet_put_string(buffer_ptr(&stdout_buffer), len);
227 packet_send();
228 buffer_consume(&stdout_buffer, len);
229 stdout_bytes += len;
230 }
231}
232
233static void
234client_alive_check(void)
235{
236 int channel_id;
237
238 /* timeout, check to see how many we have had */
239 if (++client_alive_timeouts > options.client_alive_count_max)
240 packet_disconnect("Timeout, your session not responding.");
241
242 /*
243 * send a bogus global/channel request with "wantreply",
244 * we should get back a failure
245 */
246 if ((channel_id = channel_find_open()) == -1) {
247 packet_start(SSH2_MSG_GLOBAL_REQUEST);
248 packet_put_cstring("keepalive@openssh.com");
249 packet_put_char(1); /* boolean: want reply */
250 } else {
251 channel_request_start(channel_id, "keepalive@openssh.com", 1);
252 }
253 packet_send();
254}
255
256/*
257 * Sleep in select() until we can do something. This will initialize the
258 * select masks. Upon return, the masks will indicate which descriptors
259 * have data or can accept data. Optionally, a maximum time can be specified
260 * for the duration of the wait (0 = infinite).
261 */
262static void
263wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
264 u_int *nallocp, u_int max_time_milliseconds)
265{
266 struct timeval tv, *tvp;
267 int ret;
268 int client_alive_scheduled = 0;
269
270 /*
271 * if using client_alive, set the max timeout accordingly,
272 * and indicate that this particular timeout was for client
273 * alive by setting the client_alive_scheduled flag.
274 *
275 * this could be randomized somewhat to make traffic
276 * analysis more difficult, but we're not doing it yet.
277 */
278 if (compat20 &&
279 max_time_milliseconds == 0 && options.client_alive_interval) {
280 client_alive_scheduled = 1;
281 max_time_milliseconds = options.client_alive_interval * 1000;
282 }
283
284 /* Allocate and update select() masks for channel descriptors. */
285 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
286
287 if (compat20) {
288#if 0
289 /* wrong: bad condition XXX */
290 if (channel_not_very_much_buffered_data())
291#endif
292 FD_SET(connection_in, *readsetp);
293 } else {
294 /*
295 * Read packets from the client unless we have too much
296 * buffered stdin or channel data.
297 */
298 if (buffer_len(&stdin_buffer) < buffer_high &&
299 channel_not_very_much_buffered_data())
300 FD_SET(connection_in, *readsetp);
301 /*
302 * If there is not too much data already buffered going to
303 * the client, try to get some more data from the program.
304 */
305 if (packet_not_very_much_data_to_write()) {
306 if (!fdout_eof)
307 FD_SET(fdout, *readsetp);
308 if (!fderr_eof)
309 FD_SET(fderr, *readsetp);
310 }
311 /*
312 * If we have buffered data, try to write some of that data
313 * to the program.
314 */
315 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
316 FD_SET(fdin, *writesetp);
317 }
318 notify_prepare(*readsetp);
319
320 /*
321 * If we have buffered packet data going to the client, mark that
322 * descriptor.
323 */
324 if (packet_have_data_to_write())
325 FD_SET(connection_out, *writesetp);
326
327 /*
328 * If child has terminated and there is enough buffer space to read
329 * from it, then read as much as is available and exit.
330 */
331 if (child_terminated && packet_not_very_much_data_to_write())
332 if (max_time_milliseconds == 0 || client_alive_scheduled)
333 max_time_milliseconds = 100;
334
335 if (max_time_milliseconds == 0)
336 tvp = NULL;
337 else {
338 tv.tv_sec = max_time_milliseconds / 1000;
339 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
340 tvp = &tv;
341 }
342
343 /* Wait for something to happen, or the timeout to expire. */
344 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
345
346 if (ret == -1) {
347 memset(*readsetp, 0, *nallocp);
348 memset(*writesetp, 0, *nallocp);
349 if (errno != EINTR)
350 error("select: %.100s", strerror(errno));
351 } else if (ret == 0 && client_alive_scheduled)
352 client_alive_check();
353
354 notify_done(*readsetp);
355}
356
357/*
358 * Processes input from the client and the program. Input data is stored
359 * in buffers and processed later.
360 */
361static void
362process_input(fd_set *readset)
363{
364 int len;
365 char buf[16384];
366
367 /* Read and buffer any input data from the client. */
368 if (FD_ISSET(connection_in, readset)) {
369 len = read(connection_in, buf, sizeof(buf));
370 if (len == 0) {
371 verbose("Connection closed by %.100s",
372 get_remote_ipaddr());
373 connection_closed = 1;
374 if (compat20)
375 return;
376 cleanup_exit(255);
377 } else if (len < 0) {
378 if (errno != EINTR && errno != EAGAIN) {
379 verbose("Read error from remote host "
380 "%.100s: %.100s",
381 get_remote_ipaddr(), strerror(errno));
382 cleanup_exit(255);
383 }
384 } else {
385 /* Buffer any received data. */
386 packet_process_incoming(buf, len);
387 }
388 }
389 if (compat20)
390 return;
391
392 /* Read and buffer any available stdout data from the program. */
393 if (!fdout_eof && FD_ISSET(fdout, readset)) {
394 errno = 0;
395 len = read(fdout, buf, sizeof(buf));
396 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
397 /* do nothing */
398#ifndef PTY_ZEROREAD
399 } else if (len <= 0) {
400#else
401 } else if ((!isatty(fdout) && len <= 0) ||
402 (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
403#endif
404 fdout_eof = 1;
405 } else {
406 buffer_append(&stdout_buffer, buf, len);
407 fdout_bytes += len;
408 }
409 }
410 /* Read and buffer any available stderr data from the program. */
411 if (!fderr_eof && FD_ISSET(fderr, readset)) {
412 errno = 0;
413 len = read(fderr, buf, sizeof(buf));
414 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
415 /* do nothing */
416#ifndef PTY_ZEROREAD
417 } else if (len <= 0) {
418#else
419 } else if ((!isatty(fderr) && len <= 0) ||
420 (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
421#endif
422 fderr_eof = 1;
423 } else {
424 buffer_append(&stderr_buffer, buf, len);
425 }
426 }
427}
428
429/*
430 * Sends data from internal buffers to client program stdin.
431 */
432static void
433process_output(fd_set *writeset)
434{
435 struct termios tio;
436 u_char *data;
437 u_int dlen;
438 int len;
439
440 /* Write buffered data to program stdin. */
441 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
442 data = buffer_ptr(&stdin_buffer);
443 dlen = buffer_len(&stdin_buffer);
444 len = write(fdin, data, dlen);
445 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
446 /* do nothing */
447 } else if (len <= 0) {
448 if (fdin != fdout)
449 close(fdin);
450 else
451 shutdown(fdin, SHUT_WR); /* We will no longer send. */
452 fdin = -1;
453 } else {
454 /* Successful write. */
455 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
456 tcgetattr(fdin, &tio) == 0 &&
457 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
458 /*
459 * Simulate echo to reduce the impact of
460 * traffic analysis
461 */
462 packet_send_ignore(len);
463 packet_send();
464 }
465 /* Consume the data from the buffer. */
466 buffer_consume(&stdin_buffer, len);
467 /* Update the count of bytes written to the program. */
468 stdin_bytes += len;
469 }
470 }
471 /* Send any buffered packet data to the client. */
472 if (FD_ISSET(connection_out, writeset))
473 packet_write_poll();
474}
475
476/*
477 * Wait until all buffered output has been sent to the client.
478 * This is used when the program terminates.
479 */
480static void
481drain_output(void)
482{
483 /* Send any buffered stdout data to the client. */
484 if (buffer_len(&stdout_buffer) > 0) {
485 packet_start(SSH_SMSG_STDOUT_DATA);
486 packet_put_string(buffer_ptr(&stdout_buffer),
487 buffer_len(&stdout_buffer));
488 packet_send();
489 /* Update the count of sent bytes. */
490 stdout_bytes += buffer_len(&stdout_buffer);
491 }
492 /* Send any buffered stderr data to the client. */
493 if (buffer_len(&stderr_buffer) > 0) {
494 packet_start(SSH_SMSG_STDERR_DATA);
495 packet_put_string(buffer_ptr(&stderr_buffer),
496 buffer_len(&stderr_buffer));
497 packet_send();
498 /* Update the count of sent bytes. */
499 stderr_bytes += buffer_len(&stderr_buffer);
500 }
501 /* Wait until all buffered data has been written to the client. */
502 packet_write_wait();
503}
504
505static void
506process_buffered_input_packets(void)
507{
508 dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
509}
510
511/*
512 * Performs the interactive session. This handles data transmission between
513 * the client and the program. Note that the notion of stdin, stdout, and
514 * stderr in this function is sort of reversed: this function writes to
515 * stdin (of the child program), and reads from stdout and stderr (of the
516 * child program).
517 */
518void
519server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
520{
521 fd_set *readset = NULL, *writeset = NULL;
522 int max_fd = 0;
523 u_int nalloc = 0;
524 int wait_status; /* Status returned by wait(). */
525 pid_t wait_pid; /* pid returned by wait(). */
526 int waiting_termination = 0; /* Have displayed waiting close message. */
527 u_int max_time_milliseconds;
528 u_int previous_stdout_buffer_bytes;
529 u_int stdout_buffer_bytes;
530 int type;
531
532 debug("Entering interactive session.");
533
534 /* Initialize the SIGCHLD kludge. */
535 child_terminated = 0;
536 mysignal(SIGCHLD, sigchld_handler);
537
538 if (!use_privsep) {
539 signal(SIGTERM, sigterm_handler);
540 signal(SIGINT, sigterm_handler);
541 signal(SIGQUIT, sigterm_handler);
542 }
543
544 /* Initialize our global variables. */
545 fdin = fdin_arg;
546 fdout = fdout_arg;
547 fderr = fderr_arg;
548
549 /* nonblocking IO */
550 set_nonblock(fdin);
551 set_nonblock(fdout);
552 /* we don't have stderr for interactive terminal sessions, see below */
553 if (fderr != -1)
554 set_nonblock(fderr);
555
556 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
557 fdin_is_tty = 1;
558
559 connection_in = packet_get_connection_in();
560 connection_out = packet_get_connection_out();
561
562 notify_setup();
563
564 previous_stdout_buffer_bytes = 0;
565
566 /* Set approximate I/O buffer size. */
567 if (packet_is_interactive())
568 buffer_high = 4096;
569 else
570 buffer_high = 64 * 1024;
571
572#if 0
573 /* Initialize max_fd to the maximum of the known file descriptors. */
574 max_fd = MAX(connection_in, connection_out);
575 max_fd = MAX(max_fd, fdin);
576 max_fd = MAX(max_fd, fdout);
577 if (fderr != -1)
578 max_fd = MAX(max_fd, fderr);
579#endif
580
581 /* Initialize Initialize buffers. */
582 buffer_init(&stdin_buffer);
583 buffer_init(&stdout_buffer);
584 buffer_init(&stderr_buffer);
585
586 /*
587 * If we have no separate fderr (which is the case when we have a pty
588 * - there we cannot make difference between data sent to stdout and
589 * stderr), indicate that we have seen an EOF from stderr. This way
590 * we don't need to check the descriptor everywhere.
591 */
592 if (fderr == -1)
593 fderr_eof = 1;
594
595 server_init_dispatch();
596
597 /* Main loop of the server for the interactive session mode. */
598 for (;;) {
599
600 /* Process buffered packets from the client. */
601 process_buffered_input_packets();
602
603 /*
604 * If we have received eof, and there is no more pending
605 * input data, cause a real eof by closing fdin.
606 */
607 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
608 if (fdin != fdout)
609 close(fdin);
610 else
611 shutdown(fdin, SHUT_WR); /* We will no longer send. */
612 fdin = -1;
613 }
614 /* Make packets from buffered stderr data to send to the client. */
615 make_packets_from_stderr_data();
616
617 /*
618 * Make packets from buffered stdout data to send to the
619 * client. If there is very little to send, this arranges to
620 * not send them now, but to wait a short while to see if we
621 * are getting more data. This is necessary, as some systems
622 * wake up readers from a pty after each separate character.
623 */
624 max_time_milliseconds = 0;
625 stdout_buffer_bytes = buffer_len(&stdout_buffer);
626 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
627 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
628 /* try again after a while */
629 max_time_milliseconds = 10;
630 } else {
631 /* Send it now. */
632 make_packets_from_stdout_data();
633 }
634 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
635
636 /* Send channel data to the client. */
637 if (packet_not_very_much_data_to_write())
638 channel_output_poll();
639
640 /*
641 * Bail out of the loop if the program has closed its output
642 * descriptors, and we have no more data to send to the
643 * client, and there is no pending buffered data.
644 */
645 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
646 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
647 if (!channel_still_open())
648 break;
649 if (!waiting_termination) {
650 const char *s = "Waiting for forwarded connections to terminate...\r\n";
651 char *cp;
652 waiting_termination = 1;
653 buffer_append(&stderr_buffer, s, strlen(s));
654
655 /* Display list of open channels. */
656 cp = channel_open_message();
657 buffer_append(&stderr_buffer, cp, strlen(cp));
658 xfree(cp);
659 }
660 }
661 max_fd = MAX(connection_in, connection_out);
662 max_fd = MAX(max_fd, fdin);
663 max_fd = MAX(max_fd, fdout);
664 max_fd = MAX(max_fd, fderr);
665 max_fd = MAX(max_fd, notify_pipe[0]);
666
667 /* Sleep in select() until we can do something. */
668 wait_until_can_do_something(&readset, &writeset, &max_fd,
669 &nalloc, max_time_milliseconds);
670
671 if (received_sigterm) {
672 logit("Exiting on signal %d", received_sigterm);
673 /* Clean up sessions, utmp, etc. */
674 cleanup_exit(255);
675 }
676
677 /* Process any channel events. */
678 channel_after_select(readset, writeset);
679
680 /* Process input from the client and from program stdout/stderr. */
681 process_input(readset);
682
683 /* Process output to the client and to program stdin. */
684 process_output(writeset);
685 }
686 if (readset)
687 xfree(readset);
688 if (writeset)
689 xfree(writeset);
690
691 /* Cleanup and termination code. */
692
693 /* Wait until all output has been sent to the client. */
694 drain_output();
695
696 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
697 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
698
699 /* Free and clear the buffers. */
700 buffer_free(&stdin_buffer);
701 buffer_free(&stdout_buffer);
702 buffer_free(&stderr_buffer);
703
704 /* Close the file descriptors. */
705 if (fdout != -1)
706 close(fdout);
707 fdout = -1;
708 fdout_eof = 1;
709 if (fderr != -1)
710 close(fderr);
711 fderr = -1;
712 fderr_eof = 1;
713 if (fdin != -1)
714 close(fdin);
715 fdin = -1;
716
717 channel_free_all();
718
719 /* We no longer want our SIGCHLD handler to be called. */
720 mysignal(SIGCHLD, SIG_DFL);
721
722 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
723 if (errno != EINTR)
724 packet_disconnect("wait: %.100s", strerror(errno));
725 if (wait_pid != pid)
726 error("Strange, wait returned pid %ld, expected %ld",
727 (long)wait_pid, (long)pid);
728
729 /* Check if it exited normally. */
730 if (WIFEXITED(wait_status)) {
731 /* Yes, normal exit. Get exit status and send it to the client. */
732 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
733 packet_start(SSH_SMSG_EXITSTATUS);
734 packet_put_int(WEXITSTATUS(wait_status));
735 packet_send();
736 packet_write_wait();
737
738 /*
739 * Wait for exit confirmation. Note that there might be
740 * other packets coming before it; however, the program has
741 * already died so we just ignore them. The client is
742 * supposed to respond with the confirmation when it receives
743 * the exit status.
744 */
745 do {
746 type = packet_read();
747 }
748 while (type != SSH_CMSG_EXIT_CONFIRMATION);
749
750 debug("Received exit confirmation.");
751 return;
752 }
753 /* Check if the program terminated due to a signal. */
754 if (WIFSIGNALED(wait_status))
755 packet_disconnect("Command terminated on signal %d.",
756 WTERMSIG(wait_status));
757
758 /* Some weird exit cause. Just exit. */
759 packet_disconnect("wait returned status %04x.", wait_status);
760 /* NOTREACHED */
761}
762
763static void
764collect_children(void)
765{
766 pid_t pid;
767 sigset_t oset, nset;
768 int status;
769
770 /* block SIGCHLD while we check for dead children */
771 sigemptyset(&nset);
772 sigaddset(&nset, SIGCHLD);
773 sigprocmask(SIG_BLOCK, &nset, &oset);
774 if (child_terminated) {
775 debug("Received SIGCHLD.");
776 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
777 (pid < 0 && errno == EINTR))
778 if (pid > 0)
779 session_close_by_pid(pid, status);
780 child_terminated = 0;
781 }
782 sigprocmask(SIG_SETMASK, &oset, NULL);
783}
784
785void
786server_loop2(Authctxt *authctxt)
787{
788 fd_set *readset = NULL, *writeset = NULL;
789 int rekeying = 0, max_fd, nalloc = 0;
790
791 debug("Entering interactive session for SSH2.");
792
793 mysignal(SIGCHLD, sigchld_handler);
794 child_terminated = 0;
795 connection_in = packet_get_connection_in();
796 connection_out = packet_get_connection_out();
797
798 if (!use_privsep) {
799 signal(SIGTERM, sigterm_handler);
800 signal(SIGINT, sigterm_handler);
801 signal(SIGQUIT, sigterm_handler);
802 }
803
804 notify_setup();
805
806 max_fd = MAX(connection_in, connection_out);
807 max_fd = MAX(max_fd, notify_pipe[0]);
808
809 server_init_dispatch();
810
811 for (;;) {
812 process_buffered_input_packets();
813
814 rekeying = (xxx_kex != NULL && !xxx_kex->done);
815
816 if (!rekeying && packet_not_very_much_data_to_write())
817 channel_output_poll();
818 wait_until_can_do_something(&readset, &writeset, &max_fd,
819 &nalloc, 0);
820
821 if (received_sigterm) {
822 logit("Exiting on signal %d", received_sigterm);
823 /* Clean up sessions, utmp, etc. */
824 cleanup_exit(255);
825 }
826
827 collect_children();
828 if (!rekeying) {
829 channel_after_select(readset, writeset);
830 if (packet_need_rekeying()) {
831 debug("need rekeying");
832 xxx_kex->done = 0;
833 kex_send_kexinit(xxx_kex);
834 }
835 }
836 process_input(readset);
837 if (connection_closed)
838 break;
839 process_output(writeset);
840 }
841 collect_children();
842
843 if (readset)
844 xfree(readset);
845 if (writeset)
846 xfree(writeset);
847
848 /* free all channels, no more reads and writes */
849 channel_free_all();
850
851 /* free remaining sessions, e.g. remove wtmp entries */
852 session_destroy_all(NULL);
853}
854
855static void
856server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
857{
858 debug("Got %d/%u for keepalive", type, seq);
859 /*
860 * reset timeout, since we got a sane answer from the client.
861 * even if this was generated by something other than
862 * the bogus CHANNEL_REQUEST we send for keepalives.
863 */
864 client_alive_timeouts = 0;
865}
866
867static void
868server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
869{
870 char *data;
871 u_int data_len;
872
873 /* Stdin data from the client. Append it to the buffer. */
874 /* Ignore any data if the client has closed stdin. */
875 if (fdin == -1)
876 return;
877 data = packet_get_string(&data_len);
878 packet_check_eom();
879 buffer_append(&stdin_buffer, data, data_len);
880 memset(data, 0, data_len);
881 xfree(data);
882}
883
884static void
885server_input_eof(int type, u_int32_t seq, void *ctxt)
886{
887 /*
888 * Eof from the client. The stdin descriptor to the
889 * program will be closed when all buffered data has
890 * drained.
891 */
892 debug("EOF received for stdin.");
893 packet_check_eom();
894 stdin_eof = 1;
895}
896
897static void
898server_input_window_size(int type, u_int32_t seq, void *ctxt)
899{
900 u_int row = packet_get_int();
901 u_int col = packet_get_int();
902 u_int xpixel = packet_get_int();
903 u_int ypixel = packet_get_int();
904
905 debug("Window change received.");
906 packet_check_eom();
907 if (fdin != -1)
908 pty_change_window_size(fdin, row, col, xpixel, ypixel);
909}
910
911static Channel *
912server_request_direct_tcpip(void)
913{
914 Channel *c;
915 int sock;
916 char *target, *originator;
917 int target_port, originator_port;
918
919 target = packet_get_string(NULL);
920 target_port = packet_get_int();
921 originator = packet_get_string(NULL);
922 originator_port = packet_get_int();
923 packet_check_eom();
924
925 debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
926 originator, originator_port, target, target_port);
927
928 /* XXX check permission */
929 sock = channel_connect_to(target, target_port);
930 xfree(target);
931 xfree(originator);
932 if (sock < 0)
933 return NULL;
934 c = channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING,
935 sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
936 CHAN_TCP_PACKET_DEFAULT, 0, "direct-tcpip", 1);
937 return c;
938}
939
940static Channel *
941server_request_tun(void)
942{
943 Channel *c = NULL;
944 int mode, tun;
945 int sock;
946
947 mode = packet_get_int();
948 switch (mode) {
949 case SSH_TUNMODE_POINTOPOINT:
950 case SSH_TUNMODE_ETHERNET:
951 break;
952 default:
953 packet_send_debug("Unsupported tunnel device mode.");
954 return NULL;
955 }
956 if ((options.permit_tun & mode) == 0) {
957 packet_send_debug("Server has rejected tunnel device "
958 "forwarding");
959 return NULL;
960 }
961
962 tun = packet_get_int();
963 if (forced_tun_device != -1) {
964 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
965 goto done;
966 tun = forced_tun_device;
967 }
968 sock = tun_open(tun, mode);
969 if (sock < 0)
970 goto done;
971 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
972 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
973 c->datagram = 1;
974#if defined(SSH_TUN_FILTER)
975 if (mode == SSH_TUNMODE_POINTOPOINT)
976 channel_register_filter(c->self, sys_tun_infilter,
977 sys_tun_outfilter);
978#endif
979
980 done:
981 if (c == NULL)
982 packet_send_debug("Failed to open the tunnel device.");
983 return c;
984}
985
986static Channel *
987server_request_session(void)
988{
989 Channel *c;
990
991 debug("input_session_request");
992 packet_check_eom();
993 /*
994 * A server session has no fd to read or write until a
995 * CHANNEL_REQUEST for a shell is made, so we set the type to
996 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
997 * CHANNEL_REQUEST messages is registered.
998 */
999 c = channel_new("session", SSH_CHANNEL_LARVAL,
1000 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1001 0, "server-session", 1);
1002 if (session_open(the_authctxt, c->self) != 1) {
1003 debug("session open failed, free channel %d", c->self);
1004 channel_free(c);
1005 return NULL;
1006 }
1007 channel_register_cleanup(c->self, session_close_by_channel, 0);
1008 return c;
1009}
1010
1011static void
1012server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1013{
1014 Channel *c = NULL;
1015 char *ctype;
1016 int rchan;
1017 u_int rmaxpack, rwindow, len;
1018
1019 ctype = packet_get_string(&len);
1020 rchan = packet_get_int();
1021 rwindow = packet_get_int();
1022 rmaxpack = packet_get_int();
1023
1024 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1025 ctype, rchan, rwindow, rmaxpack);
1026
1027 if (strcmp(ctype, "session") == 0) {
1028 c = server_request_session();
1029 } else if (strcmp(ctype, "direct-tcpip") == 0) {
1030 c = server_request_direct_tcpip();
1031 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1032 c = server_request_tun();
1033 }
1034 if (c != NULL) {
1035 debug("server_input_channel_open: confirm %s", ctype);
1036 c->remote_id = rchan;
1037 c->remote_window = rwindow;
1038 c->remote_maxpacket = rmaxpack;
1039 if (c->type != SSH_CHANNEL_CONNECTING) {
1040 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1041 packet_put_int(c->remote_id);
1042 packet_put_int(c->self);
1043 packet_put_int(c->local_window);
1044 packet_put_int(c->local_maxpacket);
1045 packet_send();
1046 }
1047 } else {
1048 debug("server_input_channel_open: failure %s", ctype);
1049 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1050 packet_put_int(rchan);
1051 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1052 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1053 packet_put_cstring("open failed");
1054 packet_put_cstring("");
1055 }
1056 packet_send();
1057 }
1058 xfree(ctype);
1059}
1060
1061static void
1062server_input_global_request(int type, u_int32_t seq, void *ctxt)
1063{
1064 char *rtype;
1065 int want_reply;
1066 int success = 0;
1067
1068 rtype = packet_get_string(NULL);
1069 want_reply = packet_get_char();
1070 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1071
1072 /* -R style forwarding */
1073 if (strcmp(rtype, "tcpip-forward") == 0) {
1074 struct passwd *pw;
1075 char *listen_address;
1076 u_short listen_port;
1077
1078 pw = the_authctxt->pw;
1079 if (pw == NULL || !the_authctxt->valid)
1080 fatal("server_input_global_request: no/invalid user");
1081 listen_address = packet_get_string(NULL);
1082 listen_port = (u_short)packet_get_int();
1083 debug("server_input_global_request: tcpip-forward listen %s port %d",
1084 listen_address, listen_port);
1085
1086 /* check permissions */
1087 if (!options.allow_tcp_forwarding ||
1088 no_port_forwarding_flag
1089#ifndef NO_IPPORT_RESERVED_CONCEPT
1090 || (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)
1091#endif
1092 ) {
1093 success = 0;
1094 packet_send_debug("Server has disabled port forwarding.");
1095 } else {
1096 /* Start listening on the port */
1097 success = channel_setup_remote_fwd_listener(
1098 listen_address, listen_port, options.gateway_ports);
1099 }
1100 xfree(listen_address);
1101 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1102 char *cancel_address;
1103 u_short cancel_port;
1104
1105 cancel_address = packet_get_string(NULL);
1106 cancel_port = (u_short)packet_get_int();
1107 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1108 cancel_address, cancel_port);
1109
1110 success = channel_cancel_rport_listener(cancel_address,
1111 cancel_port);
1112 xfree(cancel_address);
1113 }
1114 if (want_reply) {
1115 packet_start(success ?
1116 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1117 packet_send();
1118 packet_write_wait();
1119 }
1120 xfree(rtype);
1121}
1122
1123static void
1124server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1125{
1126 Channel *c;
1127 int id, reply, success = 0;
1128 char *rtype;
1129
1130 id = packet_get_int();
1131 rtype = packet_get_string(NULL);
1132 reply = packet_get_char();
1133
1134 debug("server_input_channel_req: channel %d request %s reply %d",
1135 id, rtype, reply);
1136
1137 if ((c = channel_lookup(id)) == NULL)
1138 packet_disconnect("server_input_channel_req: "
1139 "unknown channel %d", id);
1140 if (c->type == SSH_CHANNEL_LARVAL || c->type == SSH_CHANNEL_OPEN)
1141 success = session_input_channel_req(c, rtype);
1142 if (reply) {
1143 packet_start(success ?
1144 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1145 packet_put_int(c->remote_id);
1146 packet_send();
1147 }
1148 xfree(rtype);
1149}
1150
1151static void
1152server_init_dispatch_20(void)
1153{
1154 debug("server_init_dispatch_20");
1155 dispatch_init(&dispatch_protocol_error);
1156 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1157 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1158 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1159 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1160 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1161 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1162 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1163 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1164 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1165 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1166 /* client_alive */
1167 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1168 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1169 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1170 /* rekeying */
1171 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1172}
1173static void
1174server_init_dispatch_13(void)
1175{
1176 debug("server_init_dispatch_13");
1177 dispatch_init(NULL);
1178 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1179 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1180 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1181 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1182 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1183 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1184 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1185 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1186 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1187}
1188static void
1189server_init_dispatch_15(void)
1190{
1191 server_init_dispatch_13();
1192 debug("server_init_dispatch_15");
1193 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1194 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1195}
1196static void
1197server_init_dispatch(void)
1198{
1199 if (compat20)
1200 server_init_dispatch_20();
1201 else if (compat13)
1202 server_init_dispatch_13();
1203 else
1204 server_init_dispatch_15();
1205}
This page took 0.184272 seconds and 5 git commands to generate.