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