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