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