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