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