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