xref: /freebsd/crypto/openssh/serverloop.c (revision 2eb8169a1ad3bd8c7960767a5bc471c8d8bc677e)
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("$OpenBSD: serverloop.c,v 1.34 2000/10/27 07:32:18 markus Exp $");
39 
40 #include "xmalloc.h"
41 #include "ssh.h"
42 #include "packet.h"
43 #include "buffer.h"
44 #include "servconf.h"
45 #include "pty.h"
46 #include "channels.h"
47 
48 #include "compat.h"
49 #include "ssh2.h"
50 #include "session.h"
51 #include "dispatch.h"
52 #include "auth-options.h"
53 
54 extern ServerOptions options;
55 
56 static Buffer stdin_buffer;	/* Buffer for stdin data. */
57 static Buffer stdout_buffer;	/* Buffer for stdout data. */
58 static Buffer stderr_buffer;	/* Buffer for stderr data. */
59 static int fdin;		/* Descriptor for stdin (for writing) */
60 static int fdout;		/* Descriptor for stdout (for reading);
61 				   May be same number as fdin. */
62 static int fderr;		/* Descriptor for stderr.  May be -1. */
63 static long stdin_bytes = 0;	/* Number of bytes written to stdin. */
64 static long stdout_bytes = 0;	/* Number of stdout bytes sent to client. */
65 static long stderr_bytes = 0;	/* Number of stderr bytes sent to client. */
66 static long fdout_bytes = 0;	/* Number of stdout bytes read from program. */
67 static int stdin_eof = 0;	/* EOF message received from client. */
68 static int fdout_eof = 0;	/* EOF encountered reading from fdout. */
69 static int fderr_eof = 0;	/* EOF encountered readung from fderr. */
70 static int connection_in;	/* Connection to client (input). */
71 static int connection_out;	/* Connection to client (output). */
72 static unsigned int buffer_high;/* "Soft" max buffer size. */
73 static int max_fd;		/* Max file descriptor number for select(). */
74 
75 /*
76  * This SIGCHLD kludge is used to detect when the child exits.  The server
77  * will exit after that, as soon as forwarded connections have terminated.
78  */
79 
80 static pid_t child_pid;			/* Pid of the child. */
81 static volatile int child_terminated;	/* The child has terminated. */
82 static volatile int child_wait_status;	/* Status from wait(). */
83 
84 void	server_init_dispatch(void);
85 
86 void
87 sigchld_handler(int sig)
88 {
89 	int save_errno = errno;
90 	pid_t wait_pid;
91 
92 	debug("Received SIGCHLD.");
93 	wait_pid = wait((int *) &child_wait_status);
94 	if (wait_pid != -1) {
95 		if (wait_pid != child_pid)
96 			error("Strange, got SIGCHLD and wait returned pid %d but child is %d",
97 			      wait_pid, child_pid);
98 		if (WIFEXITED(child_wait_status) ||
99 		    WIFSIGNALED(child_wait_status))
100 			child_terminated = 1;
101 	}
102 	signal(SIGCHLD, sigchld_handler);
103 	errno = save_errno;
104 }
105 void
106 sigchld_handler2(int sig)
107 {
108 	int save_errno = errno;
109 	debug("Received SIGCHLD.");
110 	child_terminated = 1;
111 	signal(SIGCHLD, sigchld_handler2);
112 	errno = save_errno;
113 }
114 
115 /*
116  * Make packets from buffered stderr data, and buffer it for sending
117  * to the client.
118  */
119 void
120 make_packets_from_stderr_data()
121 {
122 	int len;
123 
124 	/* Send buffered stderr data to the client. */
125 	while (buffer_len(&stderr_buffer) > 0 &&
126 	    packet_not_very_much_data_to_write()) {
127 		len = buffer_len(&stderr_buffer);
128 		if (packet_is_interactive()) {
129 			if (len > 512)
130 				len = 512;
131 		} else {
132 			/* Keep the packets at reasonable size. */
133 			if (len > packet_get_maxsize())
134 				len = packet_get_maxsize();
135 		}
136 		packet_start(SSH_SMSG_STDERR_DATA);
137 		packet_put_string(buffer_ptr(&stderr_buffer), len);
138 		packet_send();
139 		buffer_consume(&stderr_buffer, len);
140 		stderr_bytes += len;
141 	}
142 }
143 
144 /*
145  * Make packets from buffered stdout data, and buffer it for sending to the
146  * client.
147  */
148 void
149 make_packets_from_stdout_data()
150 {
151 	int len;
152 
153 	/* Send buffered stdout data to the client. */
154 	while (buffer_len(&stdout_buffer) > 0 &&
155 	    packet_not_very_much_data_to_write()) {
156 		len = buffer_len(&stdout_buffer);
157 		if (packet_is_interactive()) {
158 			if (len > 512)
159 				len = 512;
160 		} else {
161 			/* Keep the packets at reasonable size. */
162 			if (len > packet_get_maxsize())
163 				len = packet_get_maxsize();
164 		}
165 		packet_start(SSH_SMSG_STDOUT_DATA);
166 		packet_put_string(buffer_ptr(&stdout_buffer), len);
167 		packet_send();
168 		buffer_consume(&stdout_buffer, len);
169 		stdout_bytes += len;
170 	}
171 }
172 
173 /*
174  * Sleep in select() until we can do something.  This will initialize the
175  * select masks.  Upon return, the masks will indicate which descriptors
176  * have data or can accept data.  Optionally, a maximum time can be specified
177  * for the duration of the wait (0 = infinite).
178  */
179 void
180 wait_until_can_do_something(fd_set * readset, fd_set * writeset,
181 			    unsigned int max_time_milliseconds)
182 {
183 	struct timeval tv, *tvp;
184 	int ret;
185 
186 	/* When select fails we restart from here. */
187 retry_select:
188 
189 	/* Initialize select() masks. */
190 	FD_ZERO(readset);
191 	FD_ZERO(writeset);
192 
193 	if (compat20) {
194 		/* wrong: bad condition XXX */
195 		if (channel_not_very_much_buffered_data())
196 			FD_SET(connection_in, readset);
197 	} else {
198 		/*
199 		 * Read packets from the client unless we have too much
200 		 * buffered stdin or channel data.
201 		 */
202 		if (buffer_len(&stdin_buffer) < buffer_high &&
203 		    channel_not_very_much_buffered_data())
204 			FD_SET(connection_in, readset);
205 		/*
206 		 * If there is not too much data already buffered going to
207 		 * the client, try to get some more data from the program.
208 		 */
209 		if (packet_not_very_much_data_to_write()) {
210 			if (!fdout_eof)
211 				FD_SET(fdout, readset);
212 			if (!fderr_eof)
213 				FD_SET(fderr, readset);
214 		}
215 		/*
216 		 * If we have buffered data, try to write some of that data
217 		 * to the program.
218 		 */
219 		if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
220 			FD_SET(fdin, writeset);
221 	}
222 	/* Set masks for channel descriptors. */
223 	channel_prepare_select(readset, writeset);
224 
225 	/*
226 	 * If we have buffered packet data going to the client, mark that
227 	 * descriptor.
228 	 */
229 	if (packet_have_data_to_write())
230 		FD_SET(connection_out, writeset);
231 
232 	/* Update the maximum descriptor number if appropriate. */
233 	if (channel_max_fd() > max_fd)
234 		max_fd = channel_max_fd();
235 
236 	/*
237 	 * If child has terminated and there is enough buffer space to read
238 	 * from it, then read as much as is available and exit.
239 	 */
240 	if (child_terminated && packet_not_very_much_data_to_write())
241 		if (max_time_milliseconds == 0)
242 			max_time_milliseconds = 100;
243 
244 	if (max_time_milliseconds == 0)
245 		tvp = NULL;
246 	else {
247 		tv.tv_sec = max_time_milliseconds / 1000;
248 		tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
249 		tvp = &tv;
250 	}
251 	if (tvp!=NULL)
252 		debug("tvp!=NULL kid %d mili %d", child_terminated, max_time_milliseconds);
253 
254 	/* Wait for something to happen, or the timeout to expire. */
255 	ret = select(max_fd + 1, readset, writeset, NULL, tvp);
256 
257 	if (ret < 0) {
258 		if (errno != EINTR)
259 			error("select: %.100s", strerror(errno));
260 		else
261 			goto retry_select;
262 	}
263 }
264 
265 /*
266  * Processes input from the client and the program.  Input data is stored
267  * in buffers and processed later.
268  */
269 void
270 process_input(fd_set * readset)
271 {
272 	int len;
273 	char buf[16384];
274 
275 	/* Read and buffer any input data from the client. */
276 	if (FD_ISSET(connection_in, readset)) {
277 		len = read(connection_in, buf, sizeof(buf));
278 		if (len == 0) {
279 			verbose("Connection closed by remote host.");
280 			fatal_cleanup();
281 		} else if (len < 0) {
282 			if (errno != EINTR && errno != EAGAIN) {
283 				verbose("Read error from remote host: %.100s", strerror(errno));
284 				fatal_cleanup();
285 			}
286 		} else {
287 			/* Buffer any received data. */
288 			packet_process_incoming(buf, len);
289 		}
290 	}
291 	if (compat20)
292 		return;
293 
294 	/* Read and buffer any available stdout data from the program. */
295 	if (!fdout_eof && FD_ISSET(fdout, readset)) {
296 		len = read(fdout, buf, sizeof(buf));
297 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
298 			/* do nothing */
299 		} else if (len <= 0) {
300 			fdout_eof = 1;
301 		} else {
302 			buffer_append(&stdout_buffer, buf, len);
303 			fdout_bytes += len;
304 		}
305 	}
306 	/* Read and buffer any available stderr data from the program. */
307 	if (!fderr_eof && FD_ISSET(fderr, readset)) {
308 		len = read(fderr, buf, sizeof(buf));
309 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
310 			/* do nothing */
311 		} else if (len <= 0) {
312 			fderr_eof = 1;
313 		} else {
314 			buffer_append(&stderr_buffer, buf, len);
315 		}
316 	}
317 }
318 
319 /*
320  * Sends data from internal buffers to client program stdin.
321  */
322 void
323 process_output(fd_set * writeset)
324 {
325 	int len;
326 
327 	/* Write buffered data to program stdin. */
328 	if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
329 		len = write(fdin, buffer_ptr(&stdin_buffer),
330 		    buffer_len(&stdin_buffer));
331 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
332 			/* do nothing */
333 		} else if (len <= 0) {
334 #ifdef USE_PIPES
335 			close(fdin);
336 #else
337 			if (fdin != fdout)
338 				close(fdin);
339 			else
340 				shutdown(fdin, SHUT_WR); /* We will no longer send. */
341 #endif
342 			fdin = -1;
343 		} else {
344 			/* Successful write.  Consume the data from the buffer. */
345 			buffer_consume(&stdin_buffer, len);
346 			/* Update the count of bytes written to the program. */
347 			stdin_bytes += len;
348 		}
349 	}
350 	/* Send any buffered packet data to the client. */
351 	if (FD_ISSET(connection_out, writeset))
352 		packet_write_poll();
353 }
354 
355 /*
356  * Wait until all buffered output has been sent to the client.
357  * This is used when the program terminates.
358  */
359 void
360 drain_output()
361 {
362 	/* Send any buffered stdout data to the client. */
363 	if (buffer_len(&stdout_buffer) > 0) {
364 		packet_start(SSH_SMSG_STDOUT_DATA);
365 		packet_put_string(buffer_ptr(&stdout_buffer),
366 				  buffer_len(&stdout_buffer));
367 		packet_send();
368 		/* Update the count of sent bytes. */
369 		stdout_bytes += buffer_len(&stdout_buffer);
370 	}
371 	/* Send any buffered stderr data to the client. */
372 	if (buffer_len(&stderr_buffer) > 0) {
373 		packet_start(SSH_SMSG_STDERR_DATA);
374 		packet_put_string(buffer_ptr(&stderr_buffer),
375 				  buffer_len(&stderr_buffer));
376 		packet_send();
377 		/* Update the count of sent bytes. */
378 		stderr_bytes += buffer_len(&stderr_buffer);
379 	}
380 	/* Wait until all buffered data has been written to the client. */
381 	packet_write_wait();
382 }
383 
384 void
385 process_buffered_input_packets()
386 {
387 	dispatch_run(DISPATCH_NONBLOCK, NULL, NULL);
388 }
389 
390 /*
391  * Performs the interactive session.  This handles data transmission between
392  * the client and the program.  Note that the notion of stdin, stdout, and
393  * stderr in this function is sort of reversed: this function writes to
394  * stdin (of the child program), and reads from stdout and stderr (of the
395  * child program).
396  */
397 void
398 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
399 {
400 	fd_set readset, writeset;
401 	int wait_status;	/* Status returned by wait(). */
402 	pid_t wait_pid;		/* pid returned by wait(). */
403 	int waiting_termination = 0;	/* Have displayed waiting close message. */
404 	unsigned int max_time_milliseconds;
405 	unsigned int previous_stdout_buffer_bytes;
406 	unsigned int stdout_buffer_bytes;
407 	int type;
408 
409 	debug("Entering interactive session.");
410 
411 	/* Initialize the SIGCHLD kludge. */
412 	child_pid = pid;
413 	child_terminated = 0;
414 	signal(SIGCHLD, sigchld_handler);
415 
416 	/* Initialize our global variables. */
417 	fdin = fdin_arg;
418 	fdout = fdout_arg;
419 	fderr = fderr_arg;
420 
421 	/* nonblocking IO */
422 	set_nonblock(fdin);
423 	set_nonblock(fdout);
424 	/* we don't have stderr for interactive terminal sessions, see below */
425 	if (fderr != -1)
426 		set_nonblock(fderr);
427 
428 	connection_in = packet_get_connection_in();
429 	connection_out = packet_get_connection_out();
430 
431 	previous_stdout_buffer_bytes = 0;
432 
433 	/* Set approximate I/O buffer size. */
434 	if (packet_is_interactive())
435 		buffer_high = 4096;
436 	else
437 		buffer_high = 64 * 1024;
438 
439 	/* Initialize max_fd to the maximum of the known file descriptors. */
440 	max_fd = fdin;
441 	if (fdout > max_fd)
442 		max_fd = fdout;
443 	if (fderr != -1 && fderr > max_fd)
444 		max_fd = fderr;
445 	if (connection_in > max_fd)
446 		max_fd = connection_in;
447 	if (connection_out > max_fd)
448 		max_fd = connection_out;
449 
450 	/* Initialize Initialize buffers. */
451 	buffer_init(&stdin_buffer);
452 	buffer_init(&stdout_buffer);
453 	buffer_init(&stderr_buffer);
454 
455 	/*
456 	 * If we have no separate fderr (which is the case when we have a pty
457 	 * - there we cannot make difference between data sent to stdout and
458 	 * stderr), indicate that we have seen an EOF from stderr.  This way
459 	 * we don\'t need to check the descriptor everywhere.
460 	 */
461 	if (fderr == -1)
462 		fderr_eof = 1;
463 
464 	server_init_dispatch();
465 
466 	/* Main loop of the server for the interactive session mode. */
467 	for (;;) {
468 
469 		/* Process buffered packets from the client. */
470 		process_buffered_input_packets();
471 
472 		/*
473 		 * If we have received eof, and there is no more pending
474 		 * input data, cause a real eof by closing fdin.
475 		 */
476 		if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
477 #ifdef USE_PIPES
478 			close(fdin);
479 #else
480 			if (fdin != fdout)
481 				close(fdin);
482 			else
483 				shutdown(fdin, SHUT_WR); /* We will no longer send. */
484 #endif
485 			fdin = -1;
486 		}
487 		/* Make packets from buffered stderr data to send to the client. */
488 		make_packets_from_stderr_data();
489 
490 		/*
491 		 * Make packets from buffered stdout data to send to the
492 		 * client. If there is very little to send, this arranges to
493 		 * not send them now, but to wait a short while to see if we
494 		 * are getting more data. This is necessary, as some systems
495 		 * wake up readers from a pty after each separate character.
496 		 */
497 		max_time_milliseconds = 0;
498 		stdout_buffer_bytes = buffer_len(&stdout_buffer);
499 		if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
500 		    stdout_buffer_bytes != previous_stdout_buffer_bytes) {
501 			/* try again after a while */
502 			max_time_milliseconds = 10;
503 		} else {
504 			/* Send it now. */
505 			make_packets_from_stdout_data();
506 		}
507 		previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
508 
509 		/* Send channel data to the client. */
510 		if (packet_not_very_much_data_to_write())
511 			channel_output_poll();
512 
513 		/*
514 		 * Bail out of the loop if the program has closed its output
515 		 * descriptors, and we have no more data to send to the
516 		 * client, and there is no pending buffered data.
517 		 */
518 		if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
519 		    buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
520 			if (!channel_still_open())
521 				break;
522 			if (!waiting_termination) {
523 				const char *s = "Waiting for forwarded connections to terminate...\r\n";
524 				char *cp;
525 				waiting_termination = 1;
526 				buffer_append(&stderr_buffer, s, strlen(s));
527 
528 				/* Display list of open channels. */
529 				cp = channel_open_message();
530 				buffer_append(&stderr_buffer, cp, strlen(cp));
531 				xfree(cp);
532 			}
533 		}
534 		/* Sleep in select() until we can do something. */
535 		wait_until_can_do_something(&readset, &writeset,
536 					    max_time_milliseconds);
537 
538 		/* Process any channel events. */
539 		channel_after_select(&readset, &writeset);
540 
541 		/* Process input from the client and from program stdout/stderr. */
542 		process_input(&readset);
543 
544 		/* Process output to the client and to program stdin. */
545 		process_output(&writeset);
546 	}
547 
548 	/* Cleanup and termination code. */
549 
550 	/* Wait until all output has been sent to the client. */
551 	drain_output();
552 
553 	debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
554 	      stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
555 
556 	/* Free and clear the buffers. */
557 	buffer_free(&stdin_buffer);
558 	buffer_free(&stdout_buffer);
559 	buffer_free(&stderr_buffer);
560 
561 	/* Close the file descriptors. */
562 	if (fdout != -1)
563 		close(fdout);
564 	fdout = -1;
565 	fdout_eof = 1;
566 	if (fderr != -1)
567 		close(fderr);
568 	fderr = -1;
569 	fderr_eof = 1;
570 	if (fdin != -1)
571 		close(fdin);
572 	fdin = -1;
573 
574 	/* Stop listening for channels; this removes unix domain sockets. */
575 	channel_stop_listening();
576 
577 	/* Wait for the child to exit.  Get its exit status. */
578 	wait_pid = wait(&wait_status);
579 	if (wait_pid < 0) {
580 		/*
581 		 * It is possible that the wait was handled by SIGCHLD
582 		 * handler.  This may result in either: this call
583 		 * returning with EINTR, or: this call returning ECHILD.
584 		 */
585 		if (child_terminated)
586 			wait_status = child_wait_status;
587 		else
588 			packet_disconnect("wait: %.100s", strerror(errno));
589 	} else {
590 		/* Check if it matches the process we forked. */
591 		if (wait_pid != pid)
592 			error("Strange, wait returned pid %d, expected %d",
593 			       wait_pid, pid);
594 	}
595 
596 	/* We no longer want our SIGCHLD handler to be called. */
597 	signal(SIGCHLD, SIG_DFL);
598 
599 	/* Check if it exited normally. */
600 	if (WIFEXITED(wait_status)) {
601 		/* Yes, normal exit.  Get exit status and send it to the client. */
602 		debug("Command exited with status %d.", WEXITSTATUS(wait_status));
603 		packet_start(SSH_SMSG_EXITSTATUS);
604 		packet_put_int(WEXITSTATUS(wait_status));
605 		packet_send();
606 		packet_write_wait();
607 
608 		/*
609 		 * Wait for exit confirmation.  Note that there might be
610 		 * other packets coming before it; however, the program has
611 		 * already died so we just ignore them.  The client is
612 		 * supposed to respond with the confirmation when it receives
613 		 * the exit status.
614 		 */
615 		do {
616 			int plen;
617 			type = packet_read(&plen);
618 		}
619 		while (type != SSH_CMSG_EXIT_CONFIRMATION);
620 
621 		debug("Received exit confirmation.");
622 		return;
623 	}
624 	/* Check if the program terminated due to a signal. */
625 	if (WIFSIGNALED(wait_status))
626 		packet_disconnect("Command terminated on signal %d.",
627 				  WTERMSIG(wait_status));
628 
629 	/* Some weird exit cause.  Just exit. */
630 	packet_disconnect("wait returned status %04x.", wait_status);
631 	/* NOTREACHED */
632 }
633 
634 void
635 server_loop2(void)
636 {
637 	fd_set readset, writeset;
638 	int had_channel = 0;
639 	int status;
640 	pid_t pid;
641 
642 	debug("Entering interactive session for SSH2.");
643 
644 	signal(SIGCHLD, sigchld_handler2);
645 	child_terminated = 0;
646 	connection_in = packet_get_connection_in();
647 	connection_out = packet_get_connection_out();
648 	max_fd = connection_in;
649 	if (connection_out > max_fd)
650 		max_fd = connection_out;
651 	server_init_dispatch();
652 
653 	for (;;) {
654 		process_buffered_input_packets();
655 		if (!had_channel && channel_still_open())
656 			had_channel = 1;
657 		if (had_channel && !channel_still_open()) {
658 			debug("!channel_still_open.");
659 			break;
660 		}
661 		if (packet_not_very_much_data_to_write())
662 			channel_output_poll();
663 		wait_until_can_do_something(&readset, &writeset, 0);
664 		if (child_terminated) {
665 			while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
666 				session_close_by_pid(pid, status);
667 			child_terminated = 0;
668 		}
669 		channel_after_select(&readset, &writeset);
670 		process_input(&readset);
671 		process_output(&writeset);
672 	}
673 	signal(SIGCHLD, SIG_DFL);
674 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
675 		session_close_by_pid(pid, status);
676 	channel_stop_listening();
677 }
678 
679 void
680 server_input_stdin_data(int type, int plen, void *ctxt)
681 {
682 	char *data;
683 	unsigned int data_len;
684 
685 	/* Stdin data from the client.  Append it to the buffer. */
686 	/* Ignore any data if the client has closed stdin. */
687 	if (fdin == -1)
688 		return;
689 	data = packet_get_string(&data_len);
690 	packet_integrity_check(plen, (4 + data_len), type);
691 	buffer_append(&stdin_buffer, data, data_len);
692 	memset(data, 0, data_len);
693 	xfree(data);
694 }
695 
696 void
697 server_input_eof(int type, int plen, void *ctxt)
698 {
699 	/*
700 	 * Eof from the client.  The stdin descriptor to the
701 	 * program will be closed when all buffered data has
702 	 * drained.
703 	 */
704 	debug("EOF received for stdin.");
705 	packet_integrity_check(plen, 0, type);
706 	stdin_eof = 1;
707 }
708 
709 void
710 server_input_window_size(int type, int plen, void *ctxt)
711 {
712 	int row = packet_get_int();
713 	int col = packet_get_int();
714 	int xpixel = packet_get_int();
715 	int ypixel = packet_get_int();
716 
717 	debug("Window change received.");
718 	packet_integrity_check(plen, 4 * 4, type);
719 	if (fdin != -1)
720 		pty_change_window_size(fdin, row, col, xpixel, ypixel);
721 }
722 
723 int
724 input_direct_tcpip(void)
725 {
726 	int sock;
727 	char *target, *originator;
728 	int target_port, originator_port;
729 
730 	target = packet_get_string(NULL);
731 	target_port = packet_get_int();
732 	originator = packet_get_string(NULL);
733 	originator_port = packet_get_int();
734 	packet_done();
735 
736 	debug("open direct-tcpip: from %s port %d to %s port %d",
737 	   originator, originator_port, target, target_port);
738 
739 	/* XXX check permission */
740 	if (no_port_forwarding_flag || !options.allow_tcp_forwarding) {
741 		xfree(target);
742 		xfree(originator);
743 		return -1;
744 	}
745 	sock = channel_connect_to(target, target_port);
746 	xfree(target);
747 	xfree(originator);
748 	if (sock < 0)
749 		return -1;
750 	return channel_new("direct-tcpip", SSH_CHANNEL_OPEN,
751 	    sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
752 	    CHAN_TCP_PACKET_DEFAULT, 0, xstrdup("direct-tcpip"), 1);
753 }
754 
755 void
756 server_input_channel_open(int type, int plen, void *ctxt)
757 {
758 	Channel *c = NULL;
759 	char *ctype;
760 	int id;
761 	unsigned int len;
762 	int rchan;
763 	int rmaxpack;
764 	int rwindow;
765 
766 	ctype = packet_get_string(&len);
767 	rchan = packet_get_int();
768 	rwindow = packet_get_int();
769 	rmaxpack = packet_get_int();
770 
771 	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
772 	    ctype, rchan, rwindow, rmaxpack);
773 
774 	if (strcmp(ctype, "session") == 0) {
775 		debug("open session");
776 		packet_done();
777 		/*
778 		 * A server session has no fd to read or write
779 		 * until a CHANNEL_REQUEST for a shell is made,
780 		 * so we set the type to SSH_CHANNEL_LARVAL.
781 		 * Additionally, a callback for handling all
782 		 * CHANNEL_REQUEST messages is registered.
783 		 */
784 		id = channel_new(ctype, SSH_CHANNEL_LARVAL,
785 		    -1, -1, -1, 0, CHAN_SES_PACKET_DEFAULT,
786 		    0, xstrdup("server-session"), 1);
787 		if (session_open(id) == 1) {
788 			channel_register_callback(id, SSH2_MSG_CHANNEL_REQUEST,
789 			    session_input_channel_req, (void *)0);
790 			channel_register_cleanup(id, session_close_by_channel);
791 			c = channel_lookup(id);
792 		} else {
793 			debug("session open failed, free channel %d", id);
794 			channel_free(id);
795 		}
796 	} else if (strcmp(ctype, "direct-tcpip") == 0) {
797 		id = input_direct_tcpip();
798 		if (id >= 0)
799 			c = channel_lookup(id);
800 	}
801 	if (c != NULL) {
802 		debug("confirm %s", ctype);
803 		c->remote_id = rchan;
804 		c->remote_window = rwindow;
805 		c->remote_maxpacket = rmaxpack;
806 
807 		packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
808 		packet_put_int(c->remote_id);
809 		packet_put_int(c->self);
810 		packet_put_int(c->local_window);
811 		packet_put_int(c->local_maxpacket);
812 		packet_send();
813 	} else {
814 		debug("failure %s", ctype);
815 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
816 		packet_put_int(rchan);
817 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
818 		packet_put_cstring("bla bla");
819 		packet_put_cstring("");
820 		packet_send();
821 	}
822 	xfree(ctype);
823 }
824 
825 void
826 server_init_dispatch_20()
827 {
828 	debug("server_init_dispatch_20");
829 	dispatch_init(&dispatch_protocol_error);
830 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
831 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
832 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
833 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
834 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
835 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
836 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
837 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &channel_input_channel_request);
838 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
839 }
840 void
841 server_init_dispatch_13()
842 {
843 	debug("server_init_dispatch_13");
844 	dispatch_init(NULL);
845 	dispatch_set(SSH_CMSG_EOF, &server_input_eof);
846 	dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
847 	dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
848 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
849 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
850 	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
851 	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
852 	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
853 	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
854 }
855 void
856 server_init_dispatch_15()
857 {
858 	server_init_dispatch_13();
859 	debug("server_init_dispatch_15");
860 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
861 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
862 }
863 void
864 server_init_dispatch()
865 {
866 	if (compat20)
867 		server_init_dispatch_20();
868 	else if (compat13)
869 		server_init_dispatch_13();
870 	else
871 		server_init_dispatch_15();
872 }
873