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