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