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