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