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