serverloop.c revision 69587
169450Smsmith/*
269450Smsmith * Author: Tatu Ylonen <ylo@cs.hut.fi>
369450Smsmith * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4151937Sjkim *                    All rights reserved
569450Smsmith * Server main loop for handling the interactive session.
669450Smsmith *
769450Smsmith * As far as I am concerned, the code I have written for this software
869450Smsmith * can be used freely for any purpose.  Any derived versions of this
969450Smsmith * software must be clearly marked as such, and if the derived work is
1069450Smsmith * incompatible with the protocol description in the RFC file, it must be
1169450Smsmith * called by a name other than "ssh" or "Secure Shell".
12151937Sjkim *
1370243Smsmith * SSH2 support by Markus Friedl.
1469450Smsmith * Copyright (c) 2000 Markus Friedl. All rights reserved.
1569450Smsmith *
1669450Smsmith * Redistribution and use in source and binary forms, with or without
1769450Smsmith * modification, are permitted provided that the following conditions
1869450Smsmith * are met:
1969450Smsmith * 1. Redistributions of source code must retain the above copyright
2069450Smsmith *    notice, this list of conditions and the following disclaimer.
2169450Smsmith * 2. Redistributions in binary form must reproduce the above copyright
2269450Smsmith *    notice, this list of conditions and the following disclaimer in the
2369450Smsmith *    documentation and/or other materials provided with the distribution.
2469450Smsmith *
2569450Smsmith * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
2669450Smsmith * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2769450Smsmith * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2869450Smsmith * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2969450Smsmith * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
3069450Smsmith * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3169450Smsmith * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3269450Smsmith * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3369450Smsmith * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3469450Smsmith * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3569450Smsmith */
3669450Smsmith
3769450Smsmith#include "includes.h"
3869450SmsmithRCSID("$OpenBSD: serverloop.c,v 1.34 2000/10/27 07:32:18 markus Exp $");
3969450Smsmith
4069450Smsmith#include "xmalloc.h"
4169450Smsmith#include "ssh.h"
4269450Smsmith#include "packet.h"
4369450Smsmith#include "buffer.h"
4469450Smsmith#include "servconf.h"
4569450Smsmith#include "pty.h"
4669450Smsmith#include "channels.h"
4769450Smsmith
4869450Smsmith#include "compat.h"
4969450Smsmith#include "ssh2.h"
5069450Smsmith#include "session.h"
5169450Smsmith#include "dispatch.h"
5269450Smsmith#include "auth-options.h"
5369450Smsmith
5469450Smsmithextern ServerOptions options;
5569450Smsmith
5669450Smsmithstatic Buffer stdin_buffer;	/* Buffer for stdin data. */
5769450Smsmithstatic Buffer stdout_buffer;	/* Buffer for stdout data. */
5869450Smsmithstatic Buffer stderr_buffer;	/* Buffer for stderr data. */
5969450Smsmithstatic int fdin;		/* Descriptor for stdin (for writing) */
6069450Smsmithstatic int fdout;		/* Descriptor for stdout (for reading);
6169450Smsmith				   May be same number as fdin. */
6269450Smsmithstatic int fderr;		/* Descriptor for stderr.  May be -1. */
6369450Smsmithstatic long stdin_bytes = 0;	/* Number of bytes written to stdin. */
6469450Smsmithstatic long stdout_bytes = 0;	/* Number of stdout bytes sent to client. */
6569450Smsmithstatic long stderr_bytes = 0;	/* Number of stderr bytes sent to client. */
6669450Smsmithstatic long fdout_bytes = 0;	/* Number of stdout bytes read from program. */
6769450Smsmithstatic int stdin_eof = 0;	/* EOF message received from client. */
6869450Smsmithstatic int fdout_eof = 0;	/* EOF encountered reading from fdout. */
6969450Smsmithstatic int fderr_eof = 0;	/* EOF encountered readung from fderr. */
7069450Smsmithstatic int connection_in;	/* Connection to client (input). */
7169450Smsmithstatic int connection_out;	/* Connection to client (output). */
7269450Smsmithstatic unsigned int buffer_high;/* "Soft" max buffer size. */
7369450Smsmithstatic int max_fd;		/* Max file descriptor number for select(). */
7469450Smsmith
7569450Smsmith/*
7669450Smsmith * This SIGCHLD kludge is used to detect when the child exits.  The server
7769450Smsmith * will exit after that, as soon as forwarded connections have terminated.
7869450Smsmith */
7969450Smsmith
8069450Smsmithstatic pid_t child_pid;			/* Pid of the child. */
8169450Smsmithstatic volatile int child_terminated;	/* The child has terminated. */
8269450Smsmithstatic volatile int child_wait_status;	/* Status from wait(). */
8369450Smsmith
8469450Smsmithvoid	server_init_dispatch(void);
8569450Smsmith
8669450Smsmithvoid
8769450Smsmithsigchld_handler(int sig)
8869450Smsmith{
8969450Smsmith	int save_errno = errno;
9069450Smsmith	pid_t wait_pid;
9169450Smsmith
9269450Smsmith	debug("Received SIGCHLD.");
9369450Smsmith	wait_pid = wait((int *) &child_wait_status);
9469450Smsmith	if (wait_pid != -1) {
9569450Smsmith		if (wait_pid != child_pid)
9669450Smsmith			error("Strange, got SIGCHLD and wait returned pid %d but child is %d",
9769450Smsmith			      wait_pid, child_pid);
9869450Smsmith		if (WIFEXITED(child_wait_status) ||
9969450Smsmith		    WIFSIGNALED(child_wait_status))
10069450Smsmith			child_terminated = 1;
10169450Smsmith	}
10269450Smsmith	signal(SIGCHLD, sigchld_handler);
10369450Smsmith	errno = save_errno;
10469450Smsmith}
10569450Smsmithvoid
10669450Smsmithsigchld_handler2(int sig)
10769450Smsmith{
10869450Smsmith	int save_errno = errno;
10969450Smsmith	debug("Received SIGCHLD.");
11069450Smsmith	child_terminated = 1;
11169450Smsmith	signal(SIGCHLD, sigchld_handler2);
11269450Smsmith	errno = save_errno;
11369450Smsmith}
11469450Smsmith
11569450Smsmith/*
11669450Smsmith * Make packets from buffered stderr data, and buffer it for sending
11769450Smsmith * to the client.
11869450Smsmith */
11969450Smsmithvoid
12069450Smsmithmake_packets_from_stderr_data()
12169450Smsmith{
12291116Smsmith	int len;
12391116Smsmith
12491116Smsmith	/* Send buffered stderr data to the client. */
125114237Snjl	while (buffer_len(&stderr_buffer) > 0 &&
12669450Smsmith	    packet_not_very_much_data_to_write()) {
127123315Snjl		len = buffer_len(&stderr_buffer);
128151937Sjkim		if (packet_is_interactive()) {
129151937Sjkim			if (len > 512)
13069450Smsmith				len = 512;
13169450Smsmith		} else {
13269450Smsmith			/* Keep the packets at reasonable size. */
13391116Smsmith			if (len > packet_get_maxsize())
13491116Smsmith				len = packet_get_maxsize();
13591116Smsmith		}
136114237Snjl		packet_start(SSH_SMSG_STDERR_DATA);
13769450Smsmith		packet_put_string(buffer_ptr(&stderr_buffer), len);
138151937Sjkim		packet_send();
139151937Sjkim		buffer_consume(&stderr_buffer, len);
14091116Smsmith		stderr_bytes += len;
14169450Smsmith	}
14269450Smsmith}
14369450Smsmith
144151937Sjkim/*
145151937Sjkim * Make packets from buffered stdout data, and buffer it for sending to the
146151937Sjkim * client.
147151937Sjkim */
148151937Sjkimvoid
149151937Sjkimmake_packets_from_stdout_data()
150151937Sjkim{
151151937Sjkim	int len;
15269450Smsmith
15369450Smsmith	/* Send buffered stdout data to the client. */
15469450Smsmith	while (buffer_len(&stdout_buffer) > 0 &&
15591116Smsmith	    packet_not_very_much_data_to_write()) {
15691116Smsmith		len = buffer_len(&stdout_buffer);
15791116Smsmith		if (packet_is_interactive()) {
158114237Snjl			if (len > 512)
15969450Smsmith				len = 512;
160123315Snjl		} else {
16169450Smsmith			/* Keep the packets at reasonable size. */
16269450Smsmith			if (len > packet_get_maxsize())
16369450Smsmith				len = packet_get_maxsize();
164151937Sjkim		}
16569450Smsmith		packet_start(SSH_SMSG_STDOUT_DATA);
16669450Smsmith		packet_put_string(buffer_ptr(&stdout_buffer), len);
16791116Smsmith		packet_send();
16891116Smsmith		buffer_consume(&stdout_buffer, len);
16969450Smsmith		stdout_bytes += len;
170151937Sjkim	}
17169450Smsmith}
17269450Smsmith
17369450Smsmith/*
17469450Smsmith * Sleep in select() until we can do something.  This will initialize the
17569450Smsmith * select masks.  Upon return, the masks will indicate which descriptors
17669450Smsmith * have data or can accept data.  Optionally, a maximum time can be specified
17769450Smsmith * for the duration of the wait (0 = infinite).
17869450Smsmith */
17969450Smsmithvoid
18069450Smsmithwait_until_can_do_something(fd_set * readset, fd_set * writeset,
18169450Smsmith			    unsigned int max_time_milliseconds)
18269450Smsmith{
18369450Smsmith	struct timeval tv, *tvp;
18469450Smsmith	int ret;
18591116Smsmith
186151937Sjkim	/* When select fails we restart from here. */
18791116Smsmithretry_select:
18891116Smsmith
18969450Smsmith	/* Initialize select() masks. */
19069450Smsmith	FD_ZERO(readset);
19191116Smsmith	FD_ZERO(writeset);
19291116Smsmith
19391116Smsmith	if (compat20) {
19491116Smsmith		/* wrong: bad condition XXX */
19591116Smsmith		if (channel_not_very_much_buffered_data())
196151937Sjkim			FD_SET(connection_in, readset);
19769450Smsmith	} else {
198151937Sjkim		/*
199151937Sjkim		 * Read packets from the client unless we have too much
200151937Sjkim		 * buffered stdin or channel data.
201151937Sjkim		 */
202151937Sjkim		if (buffer_len(&stdin_buffer) < buffer_high &&
203151937Sjkim		    channel_not_very_much_buffered_data())
204151937Sjkim			FD_SET(connection_in, readset);
205151937Sjkim		/*
206151937Sjkim		 * If there is not too much data already buffered going to
207151937Sjkim		 * the client, try to get some more data from the program.
208151937Sjkim		 */
209151937Sjkim		if (packet_not_very_much_data_to_write()) {
210151937Sjkim			if (!fdout_eof)
211151937Sjkim				FD_SET(fdout, readset);
212114237Snjl			if (!fderr_eof)
21369450Smsmith				FD_SET(fderr, readset);
21469450Smsmith		}
21569450Smsmith		/*
21669450Smsmith		 * If we have buffered data, try to write some of that data
21769450Smsmith		 * to the program.
21869450Smsmith		 */
219		if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
220			FD_SET(fdin, writeset);
221	}
222	/* Set masks for channel descriptors. */
223	channel_prepare_select(readset, writeset);
224
225	/*
226	 * If we have buffered packet data going to the client, mark that
227	 * descriptor.
228	 */
229	if (packet_have_data_to_write())
230		FD_SET(connection_out, writeset);
231
232	/* Update the maximum descriptor number if appropriate. */
233	if (channel_max_fd() > max_fd)
234		max_fd = channel_max_fd();
235
236	/*
237	 * If child has terminated and there is enough buffer space to read
238	 * from it, then read as much as is available and exit.
239	 */
240	if (child_terminated && packet_not_very_much_data_to_write())
241		if (max_time_milliseconds == 0)
242			max_time_milliseconds = 100;
243
244	if (max_time_milliseconds == 0)
245		tvp = NULL;
246	else {
247		tv.tv_sec = max_time_milliseconds / 1000;
248		tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
249		tvp = &tv;
250	}
251	if (tvp!=NULL)
252		debug("tvp!=NULL kid %d mili %d", child_terminated, max_time_milliseconds);
253
254	/* Wait for something to happen, or the timeout to expire. */
255	ret = select(max_fd + 1, readset, writeset, NULL, tvp);
256
257	if (ret < 0) {
258		if (errno != EINTR)
259			error("select: %.100s", strerror(errno));
260		else
261			goto retry_select;
262	}
263}
264
265/*
266 * Processes input from the client and the program.  Input data is stored
267 * in buffers and processed later.
268 */
269void
270process_input(fd_set * readset)
271{
272	int len;
273	char buf[16384];
274
275	/* Read and buffer any input data from the client. */
276	if (FD_ISSET(connection_in, readset)) {
277		len = read(connection_in, buf, sizeof(buf));
278		if (len == 0) {
279			verbose("Connection closed by remote host.");
280			fatal_cleanup();
281		} else if (len < 0) {
282			if (errno != EINTR && errno != EAGAIN) {
283				verbose("Read error from remote host: %.100s", strerror(errno));
284				fatal_cleanup();
285			}
286		} else {
287			/* Buffer any received data. */
288			packet_process_incoming(buf, len);
289		}
290	}
291	if (compat20)
292		return;
293
294	/* Read and buffer any available stdout data from the program. */
295	if (!fdout_eof && FD_ISSET(fdout, readset)) {
296		len = read(fdout, buf, sizeof(buf));
297		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
298			/* do nothing */
299		} else if (len <= 0) {
300			fdout_eof = 1;
301		} else {
302			buffer_append(&stdout_buffer, buf, len);
303			fdout_bytes += len;
304		}
305	}
306	/* Read and buffer any available stderr data from the program. */
307	if (!fderr_eof && FD_ISSET(fderr, readset)) {
308		len = read(fderr, buf, sizeof(buf));
309		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
310			/* do nothing */
311		} else if (len <= 0) {
312			fderr_eof = 1;
313		} else {
314			buffer_append(&stderr_buffer, buf, len);
315		}
316	}
317}
318
319/*
320 * Sends data from internal buffers to client program stdin.
321 */
322void
323process_output(fd_set * writeset)
324{
325	int len;
326
327	/* Write buffered data to program stdin. */
328	if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
329		len = write(fdin, buffer_ptr(&stdin_buffer),
330		    buffer_len(&stdin_buffer));
331		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
332			/* do nothing */
333		} else if (len <= 0) {
334#ifdef USE_PIPES
335			close(fdin);
336#else
337			if (fdin != fdout)
338				close(fdin);
339			else
340				shutdown(fdin, SHUT_WR); /* We will no longer send. */
341#endif
342			fdin = -1;
343		} else {
344			/* Successful write.  Consume the data from the buffer. */
345			buffer_consume(&stdin_buffer, len);
346			/* Update the count of bytes written to the program. */
347			stdin_bytes += len;
348		}
349	}
350	/* Send any buffered packet data to the client. */
351	if (FD_ISSET(connection_out, writeset))
352		packet_write_poll();
353}
354
355/*
356 * Wait until all buffered output has been sent to the client.
357 * This is used when the program terminates.
358 */
359void
360drain_output()
361{
362	/* Send any buffered stdout data to the client. */
363	if (buffer_len(&stdout_buffer) > 0) {
364		packet_start(SSH_SMSG_STDOUT_DATA);
365		packet_put_string(buffer_ptr(&stdout_buffer),
366				  buffer_len(&stdout_buffer));
367		packet_send();
368		/* Update the count of sent bytes. */
369		stdout_bytes += buffer_len(&stdout_buffer);
370	}
371	/* Send any buffered stderr data to the client. */
372	if (buffer_len(&stderr_buffer) > 0) {
373		packet_start(SSH_SMSG_STDERR_DATA);
374		packet_put_string(buffer_ptr(&stderr_buffer),
375				  buffer_len(&stderr_buffer));
376		packet_send();
377		/* Update the count of sent bytes. */
378		stderr_bytes += buffer_len(&stderr_buffer);
379	}
380	/* Wait until all buffered data has been written to the client. */
381	packet_write_wait();
382}
383
384void
385process_buffered_input_packets()
386{
387	dispatch_run(DISPATCH_NONBLOCK, NULL, NULL);
388}
389
390/*
391 * Performs the interactive session.  This handles data transmission between
392 * the client and the program.  Note that the notion of stdin, stdout, and
393 * stderr in this function is sort of reversed: this function writes to
394 * stdin (of the child program), and reads from stdout and stderr (of the
395 * child program).
396 */
397void
398server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
399{
400	fd_set readset, writeset;
401	int wait_status;	/* Status returned by wait(). */
402	pid_t wait_pid;		/* pid returned by wait(). */
403	int waiting_termination = 0;	/* Have displayed waiting close message. */
404	unsigned int max_time_milliseconds;
405	unsigned int previous_stdout_buffer_bytes;
406	unsigned int stdout_buffer_bytes;
407	int type;
408
409	debug("Entering interactive session.");
410
411	/* Initialize the SIGCHLD kludge. */
412	child_pid = pid;
413	child_terminated = 0;
414	signal(SIGCHLD, sigchld_handler);
415
416	/* Initialize our global variables. */
417	fdin = fdin_arg;
418	fdout = fdout_arg;
419	fderr = fderr_arg;
420
421	/* nonblocking IO */
422	set_nonblock(fdin);
423	set_nonblock(fdout);
424	/* we don't have stderr for interactive terminal sessions, see below */
425	if (fderr != -1)
426		set_nonblock(fderr);
427
428	connection_in = packet_get_connection_in();
429	connection_out = packet_get_connection_out();
430
431	previous_stdout_buffer_bytes = 0;
432
433	/* Set approximate I/O buffer size. */
434	if (packet_is_interactive())
435		buffer_high = 4096;
436	else
437		buffer_high = 64 * 1024;
438
439	/* Initialize max_fd to the maximum of the known file descriptors. */
440	max_fd = fdin;
441	if (fdout > max_fd)
442		max_fd = fdout;
443	if (fderr != -1 && fderr > max_fd)
444		max_fd = fderr;
445	if (connection_in > max_fd)
446		max_fd = connection_in;
447	if (connection_out > max_fd)
448		max_fd = connection_out;
449
450	/* Initialize Initialize buffers. */
451	buffer_init(&stdin_buffer);
452	buffer_init(&stdout_buffer);
453	buffer_init(&stderr_buffer);
454
455	/*
456	 * If we have no separate fderr (which is the case when we have a pty
457	 * - there we cannot make difference between data sent to stdout and
458	 * stderr), indicate that we have seen an EOF from stderr.  This way
459	 * we don\'t need to check the descriptor everywhere.
460	 */
461	if (fderr == -1)
462		fderr_eof = 1;
463
464	server_init_dispatch();
465
466	/* Main loop of the server for the interactive session mode. */
467	for (;;) {
468
469		/* Process buffered packets from the client. */
470		process_buffered_input_packets();
471
472		/*
473		 * If we have received eof, and there is no more pending
474		 * input data, cause a real eof by closing fdin.
475		 */
476		if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
477#ifdef USE_PIPES
478			close(fdin);
479#else
480			if (fdin != fdout)
481				close(fdin);
482			else
483				shutdown(fdin, SHUT_WR); /* We will no longer send. */
484#endif
485			fdin = -1;
486		}
487		/* Make packets from buffered stderr data to send to the client. */
488		make_packets_from_stderr_data();
489
490		/*
491		 * Make packets from buffered stdout data to send to the
492		 * client. If there is very little to send, this arranges to
493		 * not send them now, but to wait a short while to see if we
494		 * are getting more data. This is necessary, as some systems
495		 * wake up readers from a pty after each separate character.
496		 */
497		max_time_milliseconds = 0;
498		stdout_buffer_bytes = buffer_len(&stdout_buffer);
499		if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
500		    stdout_buffer_bytes != previous_stdout_buffer_bytes) {
501			/* try again after a while */
502			max_time_milliseconds = 10;
503		} else {
504			/* Send it now. */
505			make_packets_from_stdout_data();
506		}
507		previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
508
509		/* Send channel data to the client. */
510		if (packet_not_very_much_data_to_write())
511			channel_output_poll();
512
513		/*
514		 * Bail out of the loop if the program has closed its output
515		 * descriptors, and we have no more data to send to the
516		 * client, and there is no pending buffered data.
517		 */
518		if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
519		    buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
520			if (!channel_still_open())
521				break;
522			if (!waiting_termination) {
523				const char *s = "Waiting for forwarded connections to terminate...\r\n";
524				char *cp;
525				waiting_termination = 1;
526				buffer_append(&stderr_buffer, s, strlen(s));
527
528				/* Display list of open channels. */
529				cp = channel_open_message();
530				buffer_append(&stderr_buffer, cp, strlen(cp));
531				xfree(cp);
532			}
533		}
534		/* Sleep in select() until we can do something. */
535		wait_until_can_do_something(&readset, &writeset,
536					    max_time_milliseconds);
537
538		/* Process any channel events. */
539		channel_after_select(&readset, &writeset);
540
541		/* Process input from the client and from program stdout/stderr. */
542		process_input(&readset);
543
544		/* Process output to the client and to program stdin. */
545		process_output(&writeset);
546	}
547
548	/* Cleanup and termination code. */
549
550	/* Wait until all output has been sent to the client. */
551	drain_output();
552
553	debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
554	      stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
555
556	/* Free and clear the buffers. */
557	buffer_free(&stdin_buffer);
558	buffer_free(&stdout_buffer);
559	buffer_free(&stderr_buffer);
560
561	/* Close the file descriptors. */
562	if (fdout != -1)
563		close(fdout);
564	fdout = -1;
565	fdout_eof = 1;
566	if (fderr != -1)
567		close(fderr);
568	fderr = -1;
569	fderr_eof = 1;
570	if (fdin != -1)
571		close(fdin);
572	fdin = -1;
573
574	/* Stop listening for channels; this removes unix domain sockets. */
575	channel_stop_listening();
576
577	/* Wait for the child to exit.  Get its exit status. */
578	wait_pid = wait(&wait_status);
579	if (wait_pid < 0) {
580		/*
581		 * It is possible that the wait was handled by SIGCHLD
582		 * handler.  This may result in either: this call
583		 * returning with EINTR, or: this call returning ECHILD.
584		 */
585		if (child_terminated)
586			wait_status = child_wait_status;
587		else
588			packet_disconnect("wait: %.100s", strerror(errno));
589	} else {
590		/* Check if it matches the process we forked. */
591		if (wait_pid != pid)
592			error("Strange, wait returned pid %d, expected %d",
593			       wait_pid, pid);
594	}
595
596	/* We no longer want our SIGCHLD handler to be called. */
597	signal(SIGCHLD, SIG_DFL);
598
599	/* Check if it exited normally. */
600	if (WIFEXITED(wait_status)) {
601		/* Yes, normal exit.  Get exit status and send it to the client. */
602		debug("Command exited with status %d.", WEXITSTATUS(wait_status));
603		packet_start(SSH_SMSG_EXITSTATUS);
604		packet_put_int(WEXITSTATUS(wait_status));
605		packet_send();
606		packet_write_wait();
607
608		/*
609		 * Wait for exit confirmation.  Note that there might be
610		 * other packets coming before it; however, the program has
611		 * already died so we just ignore them.  The client is
612		 * supposed to respond with the confirmation when it receives
613		 * the exit status.
614		 */
615		do {
616			int plen;
617			type = packet_read(&plen);
618		}
619		while (type != SSH_CMSG_EXIT_CONFIRMATION);
620
621		debug("Received exit confirmation.");
622		return;
623	}
624	/* Check if the program terminated due to a signal. */
625	if (WIFSIGNALED(wait_status))
626		packet_disconnect("Command terminated on signal %d.",
627				  WTERMSIG(wait_status));
628
629	/* Some weird exit cause.  Just exit. */
630	packet_disconnect("wait returned status %04x.", wait_status);
631	/* NOTREACHED */
632}
633
634void
635server_loop2(void)
636{
637	fd_set readset, writeset;
638	int had_channel = 0;
639	int status;
640	pid_t pid;
641
642	debug("Entering interactive session for SSH2.");
643
644	signal(SIGCHLD, sigchld_handler2);
645	child_terminated = 0;
646	connection_in = packet_get_connection_in();
647	connection_out = packet_get_connection_out();
648	max_fd = connection_in;
649	if (connection_out > max_fd)
650		max_fd = connection_out;
651	server_init_dispatch();
652
653	for (;;) {
654		process_buffered_input_packets();
655		if (!had_channel && channel_still_open())
656			had_channel = 1;
657		if (had_channel && !channel_still_open()) {
658			debug("!channel_still_open.");
659			break;
660		}
661		if (packet_not_very_much_data_to_write())
662			channel_output_poll();
663		wait_until_can_do_something(&readset, &writeset, 0);
664		if (child_terminated) {
665			while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
666				session_close_by_pid(pid, status);
667			child_terminated = 0;
668		}
669		channel_after_select(&readset, &writeset);
670		process_input(&readset);
671		process_output(&writeset);
672	}
673	signal(SIGCHLD, SIG_DFL);
674	while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
675		session_close_by_pid(pid, status);
676	channel_stop_listening();
677}
678
679void
680server_input_stdin_data(int type, int plen, void *ctxt)
681{
682	char *data;
683	unsigned int data_len;
684
685	/* Stdin data from the client.  Append it to the buffer. */
686	/* Ignore any data if the client has closed stdin. */
687	if (fdin == -1)
688		return;
689	data = packet_get_string(&data_len);
690	packet_integrity_check(plen, (4 + data_len), type);
691	buffer_append(&stdin_buffer, data, data_len);
692	memset(data, 0, data_len);
693	xfree(data);
694}
695
696void
697server_input_eof(int type, int plen, void *ctxt)
698{
699	/*
700	 * Eof from the client.  The stdin descriptor to the
701	 * program will be closed when all buffered data has
702	 * drained.
703	 */
704	debug("EOF received for stdin.");
705	packet_integrity_check(plen, 0, type);
706	stdin_eof = 1;
707}
708
709void
710server_input_window_size(int type, int plen, void *ctxt)
711{
712	int row = packet_get_int();
713	int col = packet_get_int();
714	int xpixel = packet_get_int();
715	int ypixel = packet_get_int();
716
717	debug("Window change received.");
718	packet_integrity_check(plen, 4 * 4, type);
719	if (fdin != -1)
720		pty_change_window_size(fdin, row, col, xpixel, ypixel);
721}
722
723int
724input_direct_tcpip(void)
725{
726	int sock;
727	char *target, *originator;
728	int target_port, originator_port;
729
730	target = packet_get_string(NULL);
731	target_port = packet_get_int();
732	originator = packet_get_string(NULL);
733	originator_port = packet_get_int();
734	packet_done();
735
736	debug("open direct-tcpip: from %s port %d to %s port %d",
737	   originator, originator_port, target, target_port);
738
739	/* XXX check permission */
740	if (no_port_forwarding_flag || !options.allow_tcp_forwarding) {
741		xfree(target);
742		xfree(originator);
743		return -1;
744	}
745	sock = channel_connect_to(target, target_port);
746	xfree(target);
747	xfree(originator);
748	if (sock < 0)
749		return -1;
750	return channel_new("direct-tcpip", SSH_CHANNEL_OPEN,
751	    sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
752	    CHAN_TCP_PACKET_DEFAULT, 0, xstrdup("direct-tcpip"), 1);
753}
754
755void
756server_input_channel_open(int type, int plen, void *ctxt)
757{
758	Channel *c = NULL;
759	char *ctype;
760	int id;
761	unsigned int len;
762	int rchan;
763	int rmaxpack;
764	int rwindow;
765
766	ctype = packet_get_string(&len);
767	rchan = packet_get_int();
768	rwindow = packet_get_int();
769	rmaxpack = packet_get_int();
770
771	debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
772	    ctype, rchan, rwindow, rmaxpack);
773
774	if (strcmp(ctype, "session") == 0) {
775		debug("open session");
776		packet_done();
777		/*
778		 * A server session has no fd to read or write
779		 * until a CHANNEL_REQUEST for a shell is made,
780		 * so we set the type to SSH_CHANNEL_LARVAL.
781		 * Additionally, a callback for handling all
782		 * CHANNEL_REQUEST messages is registered.
783		 */
784		id = channel_new(ctype, SSH_CHANNEL_LARVAL,
785		    -1, -1, -1, 0, CHAN_SES_PACKET_DEFAULT,
786		    0, xstrdup("server-session"), 1);
787		if (session_open(id) == 1) {
788			channel_register_callback(id, SSH2_MSG_CHANNEL_REQUEST,
789			    session_input_channel_req, (void *)0);
790			channel_register_cleanup(id, session_close_by_channel);
791			c = channel_lookup(id);
792		} else {
793			debug("session open failed, free channel %d", id);
794			channel_free(id);
795		}
796	} else if (strcmp(ctype, "direct-tcpip") == 0) {
797		id = input_direct_tcpip();
798		if (id >= 0)
799			c = channel_lookup(id);
800	}
801	if (c != NULL) {
802		debug("confirm %s", ctype);
803		c->remote_id = rchan;
804		c->remote_window = rwindow;
805		c->remote_maxpacket = rmaxpack;
806
807		packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
808		packet_put_int(c->remote_id);
809		packet_put_int(c->self);
810		packet_put_int(c->local_window);
811		packet_put_int(c->local_maxpacket);
812		packet_send();
813	} else {
814		debug("failure %s", ctype);
815		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
816		packet_put_int(rchan);
817		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
818		packet_put_cstring("bla bla");
819		packet_put_cstring("");
820		packet_send();
821	}
822	xfree(ctype);
823}
824
825void
826server_init_dispatch_20()
827{
828	debug("server_init_dispatch_20");
829	dispatch_init(&dispatch_protocol_error);
830	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
831	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
832	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
833	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
834	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
835	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
836	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
837	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &channel_input_channel_request);
838	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
839}
840void
841server_init_dispatch_13()
842{
843	debug("server_init_dispatch_13");
844	dispatch_init(NULL);
845	dispatch_set(SSH_CMSG_EOF, &server_input_eof);
846	dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
847	dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
848	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
849	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
850	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
851	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
852	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
853	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
854}
855void
856server_init_dispatch_15()
857{
858	server_init_dispatch_13();
859	debug("server_init_dispatch_15");
860	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
861	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
862}
863void
864server_init_dispatch()
865{
866	if (compat20)
867		server_init_dispatch_20();
868	else if (compat13)
869		server_init_dispatch_13();
870	else
871		server_init_dispatch_15();
872}
873