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