xref: /openbsd-src/usr.bin/ssh/serverloop.c (revision 0eea0d082377cb9c3ec583313dc4d52b7b6a4d6d)
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.116 2004/05/21 11:33:11 djm Exp $");
39 
40 #include "xmalloc.h"
41 #include "packet.h"
42 #include "buffer.h"
43 #include "log.h"
44 #include "servconf.h"
45 #include "canohost.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 extern Authctxt *the_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 	signal(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 	u_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 	u_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 	int channel_id;
214 
215 	/* timeout, check to see how many we have had */
216 	if (++client_alive_timeouts > options.client_alive_count_max)
217 		packet_disconnect("Timeout, your session not responding.");
218 
219 	/*
220 	 * send a bogus global/channel request with "wantreply",
221 	 * we should get back a failure
222 	 */
223 	if ((channel_id = channel_find_open()) == -1) {
224 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
225 		packet_put_cstring("keepalive@openssh.com");
226 		packet_put_char(1);	/* boolean: want reply */
227 	} else {
228 		channel_request_start(channel_id, "keepalive@openssh.com", 1);
229 	}
230 	packet_send();
231 }
232 
233 /*
234  * Sleep in select() until we can do something.  This will initialize the
235  * select masks.  Upon return, the masks will indicate which descriptors
236  * have data or can accept data.  Optionally, a maximum time can be specified
237  * for the duration of the wait (0 = infinite).
238  */
239 static void
240 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
241     int *nallocp, u_int max_time_milliseconds)
242 {
243 	struct timeval tv, *tvp;
244 	int ret;
245 	int client_alive_scheduled = 0;
246 
247 	/*
248 	 * if using client_alive, set the max timeout accordingly,
249 	 * and indicate that this particular timeout was for client
250 	 * alive by setting the client_alive_scheduled flag.
251 	 *
252 	 * this could be randomized somewhat to make traffic
253 	 * analysis more difficult, but we're not doing it yet.
254 	 */
255 	if (compat20 &&
256 	    max_time_milliseconds == 0 && options.client_alive_interval) {
257 		client_alive_scheduled = 1;
258 		max_time_milliseconds = options.client_alive_interval * 1000;
259 	}
260 
261 	/* Allocate and update select() masks for channel descriptors. */
262 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
263 
264 	if (compat20) {
265 #if 0
266 		/* wrong: bad condition XXX */
267 		if (channel_not_very_much_buffered_data())
268 #endif
269 		FD_SET(connection_in, *readsetp);
270 	} else {
271 		/*
272 		 * Read packets from the client unless we have too much
273 		 * buffered stdin or channel data.
274 		 */
275 		if (buffer_len(&stdin_buffer) < buffer_high &&
276 		    channel_not_very_much_buffered_data())
277 			FD_SET(connection_in, *readsetp);
278 		/*
279 		 * If there is not too much data already buffered going to
280 		 * the client, try to get some more data from the program.
281 		 */
282 		if (packet_not_very_much_data_to_write()) {
283 			if (!fdout_eof)
284 				FD_SET(fdout, *readsetp);
285 			if (!fderr_eof)
286 				FD_SET(fderr, *readsetp);
287 		}
288 		/*
289 		 * If we have buffered data, try to write some of that data
290 		 * to the program.
291 		 */
292 		if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
293 			FD_SET(fdin, *writesetp);
294 	}
295 	notify_prepare(*readsetp);
296 
297 	/*
298 	 * If we have buffered packet data going to the client, mark that
299 	 * descriptor.
300 	 */
301 	if (packet_have_data_to_write())
302 		FD_SET(connection_out, *writesetp);
303 
304 	/*
305 	 * If child has terminated and there is enough buffer space to read
306 	 * from it, then read as much as is available and exit.
307 	 */
308 	if (child_terminated && packet_not_very_much_data_to_write())
309 		if (max_time_milliseconds == 0 || client_alive_scheduled)
310 			max_time_milliseconds = 100;
311 
312 	if (max_time_milliseconds == 0)
313 		tvp = NULL;
314 	else {
315 		tv.tv_sec = max_time_milliseconds / 1000;
316 		tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
317 		tvp = &tv;
318 	}
319 
320 	/* Wait for something to happen, or the timeout to expire. */
321 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
322 
323 	if (ret == -1) {
324 		memset(*readsetp, 0, *nallocp);
325 		memset(*writesetp, 0, *nallocp);
326 		if (errno != EINTR)
327 			error("select: %.100s", strerror(errno));
328 	} else if (ret == 0 && client_alive_scheduled)
329 		client_alive_check();
330 
331 	notify_done(*readsetp);
332 }
333 
334 /*
335  * Processes input from the client and the program.  Input data is stored
336  * in buffers and processed later.
337  */
338 static void
339 process_input(fd_set * readset)
340 {
341 	int len;
342 	char buf[16384];
343 
344 	/* Read and buffer any input data from the client. */
345 	if (FD_ISSET(connection_in, readset)) {
346 		len = read(connection_in, buf, sizeof(buf));
347 		if (len == 0) {
348 			verbose("Connection closed by %.100s",
349 			    get_remote_ipaddr());
350 			connection_closed = 1;
351 			if (compat20)
352 				return;
353 			cleanup_exit(255);
354 		} else if (len < 0) {
355 			if (errno != EINTR && errno != EAGAIN) {
356 				verbose("Read error from remote host "
357 				    "%.100s: %.100s",
358 				    get_remote_ipaddr(), strerror(errno));
359 				cleanup_exit(255);
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 	signal(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 	signal(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 	signal(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 	server_init_dispatch();
755 
756 	for (;;) {
757 		process_buffered_input_packets();
758 
759 		rekeying = (xxx_kex != NULL && !xxx_kex->done);
760 
761 		if (!rekeying && packet_not_very_much_data_to_write())
762 			channel_output_poll();
763 		wait_until_can_do_something(&readset, &writeset, &max_fd,
764 		    &nalloc, 0);
765 
766 		collect_children();
767 		if (!rekeying) {
768 			channel_after_select(readset, writeset);
769 			if (packet_need_rekeying()) {
770 				debug("need rekeying");
771 				xxx_kex->done = 0;
772 				kex_send_kexinit(xxx_kex);
773 			}
774 		}
775 		process_input(readset);
776 		if (connection_closed)
777 			break;
778 		process_output(writeset);
779 	}
780 	collect_children();
781 
782 	if (readset)
783 		xfree(readset);
784 	if (writeset)
785 		xfree(writeset);
786 
787 	/* free all channels, no more reads and writes */
788 	channel_free_all();
789 
790 	/* free remaining sessions, e.g. remove wtmp entries */
791 	session_destroy_all(NULL);
792 }
793 
794 static void
795 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
796 {
797 	debug("Got %d/%u for keepalive", type, seq);
798 	/*
799 	 * reset timeout, since we got a sane answer from the client.
800 	 * even if this was generated by something other than
801 	 * the bogus CHANNEL_REQUEST we send for keepalives.
802 	 */
803 	client_alive_timeouts = 0;
804 }
805 
806 static void
807 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
808 {
809 	char *data;
810 	u_int data_len;
811 
812 	/* Stdin data from the client.  Append it to the buffer. */
813 	/* Ignore any data if the client has closed stdin. */
814 	if (fdin == -1)
815 		return;
816 	data = packet_get_string(&data_len);
817 	packet_check_eom();
818 	buffer_append(&stdin_buffer, data, data_len);
819 	memset(data, 0, data_len);
820 	xfree(data);
821 }
822 
823 static void
824 server_input_eof(int type, u_int32_t seq, void *ctxt)
825 {
826 	/*
827 	 * Eof from the client.  The stdin descriptor to the
828 	 * program will be closed when all buffered data has
829 	 * drained.
830 	 */
831 	debug("EOF received for stdin.");
832 	packet_check_eom();
833 	stdin_eof = 1;
834 }
835 
836 static void
837 server_input_window_size(int type, u_int32_t seq, void *ctxt)
838 {
839 	int row = packet_get_int();
840 	int col = packet_get_int();
841 	int xpixel = packet_get_int();
842 	int ypixel = packet_get_int();
843 
844 	debug("Window change received.");
845 	packet_check_eom();
846 	if (fdin != -1)
847 		pty_change_window_size(fdin, row, col, xpixel, ypixel);
848 }
849 
850 static Channel *
851 server_request_direct_tcpip(void)
852 {
853 	Channel *c;
854 	int sock;
855 	char *target, *originator;
856 	int target_port, originator_port;
857 
858 	target = packet_get_string(NULL);
859 	target_port = packet_get_int();
860 	originator = packet_get_string(NULL);
861 	originator_port = packet_get_int();
862 	packet_check_eom();
863 
864 	debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
865 	   originator, originator_port, target, target_port);
866 
867 	/* XXX check permission */
868 	sock = channel_connect_to(target, target_port);
869 	xfree(target);
870 	xfree(originator);
871 	if (sock < 0)
872 		return NULL;
873 	c = channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING,
874 	    sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
875 	    CHAN_TCP_PACKET_DEFAULT, 0, "direct-tcpip", 1);
876 	return c;
877 }
878 
879 static Channel *
880 server_request_session(void)
881 {
882 	Channel *c;
883 
884 	debug("input_session_request");
885 	packet_check_eom();
886 	/*
887 	 * A server session has no fd to read or write until a
888 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
889 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
890 	 * CHANNEL_REQUEST messages is registered.
891 	 */
892 	c = channel_new("session", SSH_CHANNEL_LARVAL,
893 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
894 	    0, "server-session", 1);
895 	if (session_open(the_authctxt, c->self) != 1) {
896 		debug("session open failed, free channel %d", c->self);
897 		channel_free(c);
898 		return NULL;
899 	}
900 	channel_register_cleanup(c->self, session_close_by_channel);
901 	return c;
902 }
903 
904 static void
905 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
906 {
907 	Channel *c = NULL;
908 	char *ctype;
909 	int rchan;
910 	u_int rmaxpack, rwindow, len;
911 
912 	ctype = packet_get_string(&len);
913 	rchan = packet_get_int();
914 	rwindow = packet_get_int();
915 	rmaxpack = packet_get_int();
916 
917 	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
918 	    ctype, rchan, rwindow, rmaxpack);
919 
920 	if (strcmp(ctype, "session") == 0) {
921 		c = server_request_session();
922 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
923 		c = server_request_direct_tcpip();
924 	}
925 	if (c != NULL) {
926 		debug("server_input_channel_open: confirm %s", ctype);
927 		c->remote_id = rchan;
928 		c->remote_window = rwindow;
929 		c->remote_maxpacket = rmaxpack;
930 		if (c->type != SSH_CHANNEL_CONNECTING) {
931 			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
932 			packet_put_int(c->remote_id);
933 			packet_put_int(c->self);
934 			packet_put_int(c->local_window);
935 			packet_put_int(c->local_maxpacket);
936 			packet_send();
937 		}
938 	} else {
939 		debug("server_input_channel_open: failure %s", ctype);
940 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
941 		packet_put_int(rchan);
942 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
943 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
944 			packet_put_cstring("open failed");
945 			packet_put_cstring("");
946 		}
947 		packet_send();
948 	}
949 	xfree(ctype);
950 }
951 
952 static void
953 server_input_global_request(int type, u_int32_t seq, void *ctxt)
954 {
955 	char *rtype;
956 	int want_reply;
957 	int success = 0;
958 
959 	rtype = packet_get_string(NULL);
960 	want_reply = packet_get_char();
961 	debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
962 
963 	/* -R style forwarding */
964 	if (strcmp(rtype, "tcpip-forward") == 0) {
965 		struct passwd *pw;
966 		char *listen_address;
967 		u_short listen_port;
968 
969 		pw = the_authctxt->pw;
970 		if (pw == NULL || !the_authctxt->valid)
971 			fatal("server_input_global_request: no/invalid user");
972 		listen_address = packet_get_string(NULL);
973 		listen_port = (u_short)packet_get_int();
974 		debug("server_input_global_request: tcpip-forward listen %s port %d",
975 		    listen_address, listen_port);
976 
977 		/* check permissions */
978 		if (!options.allow_tcp_forwarding ||
979 		    no_port_forwarding_flag ||
980 		    (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)) {
981 			success = 0;
982 			packet_send_debug("Server has disabled port forwarding.");
983 		} else {
984 			/* Start listening on the port */
985 			success = channel_setup_remote_fwd_listener(
986 			    listen_address, listen_port, options.gateway_ports);
987 		}
988 		xfree(listen_address);
989 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
990 		char *cancel_address;
991 		u_short cancel_port;
992 
993 		cancel_address = packet_get_string(NULL);
994 		cancel_port = (u_short)packet_get_int();
995 		debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
996 		    cancel_address, cancel_port);
997 
998 		success = channel_cancel_rport_listener(cancel_address,
999 		    cancel_port);
1000 	}
1001 	if (want_reply) {
1002 		packet_start(success ?
1003 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1004 		packet_send();
1005 		packet_write_wait();
1006 	}
1007 	xfree(rtype);
1008 }
1009 static void
1010 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1011 {
1012 	Channel *c;
1013 	int id, reply, success = 0;
1014 	char *rtype;
1015 
1016 	id = packet_get_int();
1017 	rtype = packet_get_string(NULL);
1018 	reply = packet_get_char();
1019 
1020 	debug("server_input_channel_req: channel %d request %s reply %d",
1021 	    id, rtype, reply);
1022 
1023 	if ((c = channel_lookup(id)) == NULL)
1024 		packet_disconnect("server_input_channel_req: "
1025 		    "unknown channel %d", id);
1026 	if (c->type == SSH_CHANNEL_LARVAL || c->type == SSH_CHANNEL_OPEN)
1027 		success = session_input_channel_req(c, rtype);
1028 	if (reply) {
1029 		packet_start(success ?
1030 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1031 		packet_put_int(c->remote_id);
1032 		packet_send();
1033 	}
1034 	xfree(rtype);
1035 }
1036 
1037 static void
1038 server_init_dispatch_20(void)
1039 {
1040 	debug("server_init_dispatch_20");
1041 	dispatch_init(&dispatch_protocol_error);
1042 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1043 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1044 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1045 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1046 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1047 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1048 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1049 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1050 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1051 	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1052 	/* client_alive */
1053 	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1054 	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1055 	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1056 	/* rekeying */
1057 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1058 }
1059 static void
1060 server_init_dispatch_13(void)
1061 {
1062 	debug("server_init_dispatch_13");
1063 	dispatch_init(NULL);
1064 	dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1065 	dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1066 	dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1067 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1068 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1069 	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1070 	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1071 	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1072 	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1073 }
1074 static void
1075 server_init_dispatch_15(void)
1076 {
1077 	server_init_dispatch_13();
1078 	debug("server_init_dispatch_15");
1079 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1080 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1081 }
1082 static void
1083 server_init_dispatch(void)
1084 {
1085 	if (compat20)
1086 		server_init_dispatch_20();
1087 	else if (compat13)
1088 		server_init_dispatch_13();
1089 	else
1090 		server_init_dispatch_15();
1091 }
1092