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