xref: /openbsd-src/usr.bin/ssh/serverloop.c (revision 11efff7f3ac2b3cfeff0c0cddc14294d9b3aca4f)
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.117 2004/08/11 21:43:05 avsm 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     u_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;
488 	u_int nalloc = 0;
489 	int wait_status;	/* Status returned by wait(). */
490 	pid_t wait_pid;		/* pid returned by wait(). */
491 	int waiting_termination = 0;	/* Have displayed waiting close message. */
492 	u_int max_time_milliseconds;
493 	u_int previous_stdout_buffer_bytes;
494 	u_int stdout_buffer_bytes;
495 	int type;
496 
497 	debug("Entering interactive session.");
498 
499 	/* Initialize the SIGCHLD kludge. */
500 	child_terminated = 0;
501 	signal(SIGCHLD, sigchld_handler);
502 
503 	/* Initialize our global variables. */
504 	fdin = fdin_arg;
505 	fdout = fdout_arg;
506 	fderr = fderr_arg;
507 
508 	/* nonblocking IO */
509 	set_nonblock(fdin);
510 	set_nonblock(fdout);
511 	/* we don't have stderr for interactive terminal sessions, see below */
512 	if (fderr != -1)
513 		set_nonblock(fderr);
514 
515 	if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
516 		fdin_is_tty = 1;
517 
518 	connection_in = packet_get_connection_in();
519 	connection_out = packet_get_connection_out();
520 
521 	notify_setup();
522 
523 	previous_stdout_buffer_bytes = 0;
524 
525 	/* Set approximate I/O buffer size. */
526 	if (packet_is_interactive())
527 		buffer_high = 4096;
528 	else
529 		buffer_high = 64 * 1024;
530 
531 #if 0
532 	/* Initialize max_fd to the maximum of the known file descriptors. */
533 	max_fd = MAX(connection_in, connection_out);
534 	max_fd = MAX(max_fd, fdin);
535 	max_fd = MAX(max_fd, fdout);
536 	if (fderr != -1)
537 		max_fd = MAX(max_fd, fderr);
538 #endif
539 
540 	/* Initialize Initialize buffers. */
541 	buffer_init(&stdin_buffer);
542 	buffer_init(&stdout_buffer);
543 	buffer_init(&stderr_buffer);
544 
545 	/*
546 	 * If we have no separate fderr (which is the case when we have a pty
547 	 * - there we cannot make difference between data sent to stdout and
548 	 * stderr), indicate that we have seen an EOF from stderr.  This way
549 	 * we don\'t need to check the descriptor everywhere.
550 	 */
551 	if (fderr == -1)
552 		fderr_eof = 1;
553 
554 	server_init_dispatch();
555 
556 	/* Main loop of the server for the interactive session mode. */
557 	for (;;) {
558 
559 		/* Process buffered packets from the client. */
560 		process_buffered_input_packets();
561 
562 		/*
563 		 * If we have received eof, and there is no more pending
564 		 * input data, cause a real eof by closing fdin.
565 		 */
566 		if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
567 			if (fdin != fdout)
568 				close(fdin);
569 			else
570 				shutdown(fdin, SHUT_WR); /* We will no longer send. */
571 			fdin = -1;
572 		}
573 		/* Make packets from buffered stderr data to send to the client. */
574 		make_packets_from_stderr_data();
575 
576 		/*
577 		 * Make packets from buffered stdout data to send to the
578 		 * client. If there is very little to send, this arranges to
579 		 * not send them now, but to wait a short while to see if we
580 		 * are getting more data. This is necessary, as some systems
581 		 * wake up readers from a pty after each separate character.
582 		 */
583 		max_time_milliseconds = 0;
584 		stdout_buffer_bytes = buffer_len(&stdout_buffer);
585 		if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
586 		    stdout_buffer_bytes != previous_stdout_buffer_bytes) {
587 			/* try again after a while */
588 			max_time_milliseconds = 10;
589 		} else {
590 			/* Send it now. */
591 			make_packets_from_stdout_data();
592 		}
593 		previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
594 
595 		/* Send channel data to the client. */
596 		if (packet_not_very_much_data_to_write())
597 			channel_output_poll();
598 
599 		/*
600 		 * Bail out of the loop if the program has closed its output
601 		 * descriptors, and we have no more data to send to the
602 		 * client, and there is no pending buffered data.
603 		 */
604 		if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
605 		    buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
606 			if (!channel_still_open())
607 				break;
608 			if (!waiting_termination) {
609 				const char *s = "Waiting for forwarded connections to terminate...\r\n";
610 				char *cp;
611 				waiting_termination = 1;
612 				buffer_append(&stderr_buffer, s, strlen(s));
613 
614 				/* Display list of open channels. */
615 				cp = channel_open_message();
616 				buffer_append(&stderr_buffer, cp, strlen(cp));
617 				xfree(cp);
618 			}
619 		}
620 		max_fd = MAX(connection_in, connection_out);
621 		max_fd = MAX(max_fd, fdin);
622 		max_fd = MAX(max_fd, fdout);
623 		max_fd = MAX(max_fd, fderr);
624 		max_fd = MAX(max_fd, notify_pipe[0]);
625 
626 		/* Sleep in select() until we can do something. */
627 		wait_until_can_do_something(&readset, &writeset, &max_fd,
628 		    &nalloc, max_time_milliseconds);
629 
630 		/* Process any channel events. */
631 		channel_after_select(readset, writeset);
632 
633 		/* Process input from the client and from program stdout/stderr. */
634 		process_input(readset);
635 
636 		/* Process output to the client and to program stdin. */
637 		process_output(writeset);
638 	}
639 	if (readset)
640 		xfree(readset);
641 	if (writeset)
642 		xfree(writeset);
643 
644 	/* Cleanup and termination code. */
645 
646 	/* Wait until all output has been sent to the client. */
647 	drain_output();
648 
649 	debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
650 	    stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
651 
652 	/* Free and clear the buffers. */
653 	buffer_free(&stdin_buffer);
654 	buffer_free(&stdout_buffer);
655 	buffer_free(&stderr_buffer);
656 
657 	/* Close the file descriptors. */
658 	if (fdout != -1)
659 		close(fdout);
660 	fdout = -1;
661 	fdout_eof = 1;
662 	if (fderr != -1)
663 		close(fderr);
664 	fderr = -1;
665 	fderr_eof = 1;
666 	if (fdin != -1)
667 		close(fdin);
668 	fdin = -1;
669 
670 	channel_free_all();
671 
672 	/* We no longer want our SIGCHLD handler to be called. */
673 	signal(SIGCHLD, SIG_DFL);
674 
675 	while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
676 		if (errno != EINTR)
677 			packet_disconnect("wait: %.100s", strerror(errno));
678 	if (wait_pid != pid)
679 		error("Strange, wait returned pid %ld, expected %ld",
680 		    (long)wait_pid, (long)pid);
681 
682 	/* Check if it exited normally. */
683 	if (WIFEXITED(wait_status)) {
684 		/* Yes, normal exit.  Get exit status and send it to the client. */
685 		debug("Command exited with status %d.", WEXITSTATUS(wait_status));
686 		packet_start(SSH_SMSG_EXITSTATUS);
687 		packet_put_int(WEXITSTATUS(wait_status));
688 		packet_send();
689 		packet_write_wait();
690 
691 		/*
692 		 * Wait for exit confirmation.  Note that there might be
693 		 * other packets coming before it; however, the program has
694 		 * already died so we just ignore them.  The client is
695 		 * supposed to respond with the confirmation when it receives
696 		 * the exit status.
697 		 */
698 		do {
699 			type = packet_read();
700 		}
701 		while (type != SSH_CMSG_EXIT_CONFIRMATION);
702 
703 		debug("Received exit confirmation.");
704 		return;
705 	}
706 	/* Check if the program terminated due to a signal. */
707 	if (WIFSIGNALED(wait_status))
708 		packet_disconnect("Command terminated on signal %d.",
709 				  WTERMSIG(wait_status));
710 
711 	/* Some weird exit cause.  Just exit. */
712 	packet_disconnect("wait returned status %04x.", wait_status);
713 	/* NOTREACHED */
714 }
715 
716 static void
717 collect_children(void)
718 {
719 	pid_t pid;
720 	sigset_t oset, nset;
721 	int status;
722 
723 	/* block SIGCHLD while we check for dead children */
724 	sigemptyset(&nset);
725 	sigaddset(&nset, SIGCHLD);
726 	sigprocmask(SIG_BLOCK, &nset, &oset);
727 	if (child_terminated) {
728 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
729 		    (pid < 0 && errno == EINTR))
730 			if (pid > 0)
731 				session_close_by_pid(pid, status);
732 		child_terminated = 0;
733 	}
734 	sigprocmask(SIG_SETMASK, &oset, NULL);
735 }
736 
737 void
738 server_loop2(Authctxt *authctxt)
739 {
740 	fd_set *readset = NULL, *writeset = NULL;
741 	int rekeying = 0, max_fd, nalloc = 0;
742 
743 	debug("Entering interactive session for SSH2.");
744 
745 	signal(SIGCHLD, sigchld_handler);
746 	child_terminated = 0;
747 	connection_in = packet_get_connection_in();
748 	connection_out = packet_get_connection_out();
749 
750 	notify_setup();
751 
752 	max_fd = MAX(connection_in, connection_out);
753 	max_fd = MAX(max_fd, notify_pipe[0]);
754 
755 	server_init_dispatch();
756 
757 	for (;;) {
758 		process_buffered_input_packets();
759 
760 		rekeying = (xxx_kex != NULL && !xxx_kex->done);
761 
762 		if (!rekeying && packet_not_very_much_data_to_write())
763 			channel_output_poll();
764 		wait_until_can_do_something(&readset, &writeset, &max_fd,
765 		    &nalloc, 0);
766 
767 		collect_children();
768 		if (!rekeying) {
769 			channel_after_select(readset, writeset);
770 			if (packet_need_rekeying()) {
771 				debug("need rekeying");
772 				xxx_kex->done = 0;
773 				kex_send_kexinit(xxx_kex);
774 			}
775 		}
776 		process_input(readset);
777 		if (connection_closed)
778 			break;
779 		process_output(writeset);
780 	}
781 	collect_children();
782 
783 	if (readset)
784 		xfree(readset);
785 	if (writeset)
786 		xfree(writeset);
787 
788 	/* free all channels, no more reads and writes */
789 	channel_free_all();
790 
791 	/* free remaining sessions, e.g. remove wtmp entries */
792 	session_destroy_all(NULL);
793 }
794 
795 static void
796 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
797 {
798 	debug("Got %d/%u for keepalive", type, seq);
799 	/*
800 	 * reset timeout, since we got a sane answer from the client.
801 	 * even if this was generated by something other than
802 	 * the bogus CHANNEL_REQUEST we send for keepalives.
803 	 */
804 	client_alive_timeouts = 0;
805 }
806 
807 static void
808 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
809 {
810 	char *data;
811 	u_int data_len;
812 
813 	/* Stdin data from the client.  Append it to the buffer. */
814 	/* Ignore any data if the client has closed stdin. */
815 	if (fdin == -1)
816 		return;
817 	data = packet_get_string(&data_len);
818 	packet_check_eom();
819 	buffer_append(&stdin_buffer, data, data_len);
820 	memset(data, 0, data_len);
821 	xfree(data);
822 }
823 
824 static void
825 server_input_eof(int type, u_int32_t seq, void *ctxt)
826 {
827 	/*
828 	 * Eof from the client.  The stdin descriptor to the
829 	 * program will be closed when all buffered data has
830 	 * drained.
831 	 */
832 	debug("EOF received for stdin.");
833 	packet_check_eom();
834 	stdin_eof = 1;
835 }
836 
837 static void
838 server_input_window_size(int type, u_int32_t seq, void *ctxt)
839 {
840 	int row = packet_get_int();
841 	int col = packet_get_int();
842 	int xpixel = packet_get_int();
843 	int ypixel = packet_get_int();
844 
845 	debug("Window change received.");
846 	packet_check_eom();
847 	if (fdin != -1)
848 		pty_change_window_size(fdin, row, col, xpixel, ypixel);
849 }
850 
851 static Channel *
852 server_request_direct_tcpip(void)
853 {
854 	Channel *c;
855 	int sock;
856 	char *target, *originator;
857 	int target_port, originator_port;
858 
859 	target = packet_get_string(NULL);
860 	target_port = packet_get_int();
861 	originator = packet_get_string(NULL);
862 	originator_port = packet_get_int();
863 	packet_check_eom();
864 
865 	debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
866 	   originator, originator_port, target, target_port);
867 
868 	/* XXX check permission */
869 	sock = channel_connect_to(target, target_port);
870 	xfree(target);
871 	xfree(originator);
872 	if (sock < 0)
873 		return NULL;
874 	c = channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING,
875 	    sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
876 	    CHAN_TCP_PACKET_DEFAULT, 0, "direct-tcpip", 1);
877 	return c;
878 }
879 
880 static Channel *
881 server_request_session(void)
882 {
883 	Channel *c;
884 
885 	debug("input_session_request");
886 	packet_check_eom();
887 	/*
888 	 * A server session has no fd to read or write until a
889 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
890 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
891 	 * CHANNEL_REQUEST messages is registered.
892 	 */
893 	c = channel_new("session", SSH_CHANNEL_LARVAL,
894 	    -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
895 	    0, "server-session", 1);
896 	if (session_open(the_authctxt, c->self) != 1) {
897 		debug("session open failed, free channel %d", c->self);
898 		channel_free(c);
899 		return NULL;
900 	}
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 	int rchan;
911 	u_int rmaxpack, rwindow, len;
912 
913 	ctype = packet_get_string(&len);
914 	rchan = packet_get_int();
915 	rwindow = packet_get_int();
916 	rmaxpack = packet_get_int();
917 
918 	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
919 	    ctype, rchan, rwindow, rmaxpack);
920 
921 	if (strcmp(ctype, "session") == 0) {
922 		c = server_request_session();
923 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
924 		c = server_request_direct_tcpip();
925 	}
926 	if (c != NULL) {
927 		debug("server_input_channel_open: confirm %s", ctype);
928 		c->remote_id = rchan;
929 		c->remote_window = rwindow;
930 		c->remote_maxpacket = rmaxpack;
931 		if (c->type != SSH_CHANNEL_CONNECTING) {
932 			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
933 			packet_put_int(c->remote_id);
934 			packet_put_int(c->self);
935 			packet_put_int(c->local_window);
936 			packet_put_int(c->local_maxpacket);
937 			packet_send();
938 		}
939 	} else {
940 		debug("server_input_channel_open: failure %s", ctype);
941 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
942 		packet_put_int(rchan);
943 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
944 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
945 			packet_put_cstring("open failed");
946 			packet_put_cstring("");
947 		}
948 		packet_send();
949 	}
950 	xfree(ctype);
951 }
952 
953 static void
954 server_input_global_request(int type, u_int32_t seq, void *ctxt)
955 {
956 	char *rtype;
957 	int want_reply;
958 	int success = 0;
959 
960 	rtype = packet_get_string(NULL);
961 	want_reply = packet_get_char();
962 	debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
963 
964 	/* -R style forwarding */
965 	if (strcmp(rtype, "tcpip-forward") == 0) {
966 		struct passwd *pw;
967 		char *listen_address;
968 		u_short listen_port;
969 
970 		pw = the_authctxt->pw;
971 		if (pw == NULL || !the_authctxt->valid)
972 			fatal("server_input_global_request: no/invalid user");
973 		listen_address = packet_get_string(NULL);
974 		listen_port = (u_short)packet_get_int();
975 		debug("server_input_global_request: tcpip-forward listen %s port %d",
976 		    listen_address, listen_port);
977 
978 		/* check permissions */
979 		if (!options.allow_tcp_forwarding ||
980 		    no_port_forwarding_flag ||
981 		    (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)) {
982 			success = 0;
983 			packet_send_debug("Server has disabled port forwarding.");
984 		} else {
985 			/* Start listening on the port */
986 			success = channel_setup_remote_fwd_listener(
987 			    listen_address, listen_port, options.gateway_ports);
988 		}
989 		xfree(listen_address);
990 	} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
991 		char *cancel_address;
992 		u_short cancel_port;
993 
994 		cancel_address = packet_get_string(NULL);
995 		cancel_port = (u_short)packet_get_int();
996 		debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
997 		    cancel_address, cancel_port);
998 
999 		success = channel_cancel_rport_listener(cancel_address,
1000 		    cancel_port);
1001 	}
1002 	if (want_reply) {
1003 		packet_start(success ?
1004 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1005 		packet_send();
1006 		packet_write_wait();
1007 	}
1008 	xfree(rtype);
1009 }
1010 static void
1011 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1012 {
1013 	Channel *c;
1014 	int id, reply, success = 0;
1015 	char *rtype;
1016 
1017 	id = packet_get_int();
1018 	rtype = packet_get_string(NULL);
1019 	reply = packet_get_char();
1020 
1021 	debug("server_input_channel_req: channel %d request %s reply %d",
1022 	    id, rtype, reply);
1023 
1024 	if ((c = channel_lookup(id)) == NULL)
1025 		packet_disconnect("server_input_channel_req: "
1026 		    "unknown channel %d", id);
1027 	if (c->type == SSH_CHANNEL_LARVAL || c->type == SSH_CHANNEL_OPEN)
1028 		success = session_input_channel_req(c, rtype);
1029 	if (reply) {
1030 		packet_start(success ?
1031 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1032 		packet_put_int(c->remote_id);
1033 		packet_send();
1034 	}
1035 	xfree(rtype);
1036 }
1037 
1038 static void
1039 server_init_dispatch_20(void)
1040 {
1041 	debug("server_init_dispatch_20");
1042 	dispatch_init(&dispatch_protocol_error);
1043 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1044 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1045 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1046 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1047 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1048 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1049 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1050 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1051 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1052 	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1053 	/* client_alive */
1054 	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1055 	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1056 	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1057 	/* rekeying */
1058 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1059 }
1060 static void
1061 server_init_dispatch_13(void)
1062 {
1063 	debug("server_init_dispatch_13");
1064 	dispatch_init(NULL);
1065 	dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1066 	dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1067 	dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1068 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1069 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1070 	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1071 	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1072 	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1073 	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1074 }
1075 static void
1076 server_init_dispatch_15(void)
1077 {
1078 	server_init_dispatch_13();
1079 	debug("server_init_dispatch_15");
1080 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1081 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1082 }
1083 static void
1084 server_init_dispatch(void)
1085 {
1086 	if (compat20)
1087 		server_init_dispatch_20();
1088 	else if (compat13)
1089 		server_init_dispatch_13();
1090 	else
1091 		server_init_dispatch_15();
1092 }
1093