/*
 * NAME:
 *	SSLrshd - SSL based rshd
 *
 * DESCRIPTION:
 *	We do away with most of the rsh protocol, we do not use
 *	hosts.equiv or .rhosts files.  ssld_start() ensures we get a
 *	valid certificate from the client and ssld_auth() looks up
 *	that cert and the desired local user to see if permission
 *	should be granted.
 *
 * BUGS:
 *	We need to run the command as a child, so we can do the
 *	encryption.  A socketpair() for stdin/out is the go, but
 *	apparently everything prior to 4.4BSD does not do shutdown()
 *	right.  To make matters worse, we can use separate pipes for
 *	stdin/stdout as rcp and other network servers expect to be
 *	able to write to fd 0.  Its a real bitch.  The only good news
 *	is that rcp and rdist do not use a separate stderr, so we can
 *	use that as a clue - if no 2nd channel, then use a
 *	socketpair(), otherwise use 3 pipes.
 *
 *	If SHUTDOWN_HACK is defined and we are using a socketpair; if
 *	the command being run is just a shell we send it and ``exit'',
 *	otherwise we set a 1 minute timeout - to commit suicide.
 *	
 *	To allow for use from cron etc, we allow host certificates to
 *	be used (with un-encrypted private keys).  These should
 *	only be available to the super user on a UNIX system and
 *	before accepting one we check that it is being used from the
 *	host it was issued to (as best we can).
 *
 * AUTHOR:
 *	Hacked from BSD rshd by Simon J. Gerraty <sjg@quick.com.au>
 *	There's just enough of the original code to warrant a copyright
 *	notice.
 */
/*-
 * Copyright (c) 1996 Simon J. Gerraty, all rights reserved.
 * Copyright (c) 1988, 1989, 1992, 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef lint
static char copyright[] =
"@(#) Copyright (c) 1988, 1989, 1992, 1993, 1994\n\
	The Regents of the University of California.  All rights reserved.\n";
#endif /* not lint */

#ifndef lint
/* from: static char sccsid[] = "@(#)rshd.c	8.2 (Berkeley) 4/6/94"; */
static char *rcsid = "$Id: rshd.c,v 1.26 1997/02/08 07:12:35 sjg Exp $";
#endif /* not lint */

/*
 * SSL remote shell server:
 *	\0
 *	remuser\0
 *	locuser\0
 *	command\0
 *	data
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/types.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>

#include "sslfd.h"

#ifdef sun
# include "sunos.h"
#endif

/*
 * A simple test of shutdown() on a socketpair() fails on SunOS 4.X
 * Solaris 2.5 passes but, the following is still necessary.
 * Define NO_SHUTDOWN_HACK if you want to sort it out.
 */
#if defined(sun) || defined(__hpux__)
# ifndef NO_SHUTDOWN_HACK
#   define SHUTOWN_HACK
# endif
#endif

int	keepalive = 1;
int	check_all;
int	log_success;		/* If TRUE, log all successful accesses */
int	sent_null;
int	use_user_shell = 1;
int	use_socketpair = 0;

void	 doit __P((struct sockaddr_in *));
void	 error __P((const char *, ...));
void	 getstr __P((char *, int, char *));
int	 local_domain __P((char *));
char	*topdomain __P((char *));
void	 usage __P((void));

char *_path_defpath = _PATH_DEFPATH;

#define OPTIONS "R:z:anLP:p:dD:t:s"
#define MYNAME "SSLrshd"


#define OPTARG_VAL(str, cp, key) ((cp = strchr(str, '=')) && strncmp(str, key, cp - str) == 0 && ++cp)

/*
 * <sjg> like ftpchroot.
 * If target user is named in _PATH_RSHCHROOT then just before
 * invoking their command we chroot to their home directory or the
 * directory named in _PATH_RSHCHROOT. 
 * If chroot(2) fails we log it and exit.
 * Example:
 * nobody:/chroot/goal
 * fred:/chroot/goal
 * sjg
 *
 * fred and nobody will chroot(/chroot/goal), while sjg will
 * chroot(~sjg). 
 */
#ifndef _PATH_RSHCHROOT
# define _PATH_RSHCHROOT "/etc/rshchroot"
#endif
/* so we can change it */
static char *_path_rshchroot = _PATH_RSHCHROOT;

int
rsh_chroot(pwd)
	struct passwd *pwd;
{
	FILE *fh;
	char *cp, buf[128];
	int line = 0;

	if (!pwd || !_path_rshchroot)
		return 0;
	
	if (fh = fopen(_path_rshchroot, "r")) {
		while (fgets(buf, sizeof(buf), fh)) {
			line++;
			switch (buf[0]) {
			case '#':
			case '\t':
			case '\n':
				continue;
			}
			if (cp = strrchr(buf, '\n'))
				*cp = '\0';
			else {
				syslog(LOG_WARNING, "%s: line %d too long",
				       _path_rshchroot, line);
				continue;
			}
			if (cp = strchr(buf, ':'))
				*cp++ = '\0';
			else
				cp = pwd->pw_dir;
			if (strcmp(buf, pwd->pw_name) == 0) {
				/* yes, chroot */
				fclose(fh);
				if (chroot(cp) < 0) {
					error("No remote directory.\n");
					syslog(LOG_NOTICE|LOG_AUTH,
					       "%s: cannot chroot(%s)",
					       pwd->pw_name, cp);
					exit(1);
				}
				syslog(LOG_INFO, "%s: chroot(%s)",
				       pwd->pw_name, cp);
				return 1;
			}
		}
		fclose(fh);
	}
	return 0;
}

#ifdef DEBUG
int
r_log(fd, buf, bytes, flags)
	int fd, bytes, flags;
	char *buf;
{
	syslog(LOG_DEBUG, "read(%d, \"%.*s\", %d)", fd,
	       bytes > 10 ? 10 : bytes,
	       buf, bytes);
	return bytes;
}

int
w_log(fd, buf, bytes, flags)
	int fd, bytes, flags;
	char *buf;
{
	syslog(LOG_DEBUG, "write(%d, \"%.*s\", %d)", fd,
	       bytes > 10 ? 10 : bytes,
	       buf, bytes); 
	return bytes;
}
#endif

void
sigalrm(s)
	int s;
{
	syslog(LOG_WARNING, "timeout");
	exit(1);
}

int
main(argc, argv)
	int argc;
	char *argv[];
{
#ifdef DEBUG
	extern int Debug;
#endif
	struct linger linger;
	int ch, on = 1, fromlen;
	struct sockaddr_in me, from;
	char		*cp;
	/* use defaults in ssld.c */
	char		*cipher_list = 0;
	char		*cert_file = 0;
	char		*key_file = 0;
	int		verify_flag = -1;
	int		port = -1, s;
	char		*log_fac = "daemon";

	opterr = 0;
	while ((ch = getopt(argc, argv, OPTIONS)) != EOF)
		switch (ch) {
		case 's':
			use_user_shell=0;
			break;
		case 't':
			/* set a read timeout, we die if it goes off */
			copy_timeout(atoi(optarg));
			signal(SIGALRM, sigalrm);
			break;
		case 'R':
			_path_rshchroot = optarg;
			break;
		case 'd':
#ifdef DEBUG
			Debug = 1;	/* prevent inetd_init() forking */
		{
			extern int (*readnet_hook)();
			extern int (*writenet_hook)();

			readnet_hook = r_log;
			writenet_hook = w_log;
		}
#endif
			break;
		case 'D':
			port = atoi(optarg);
			break;
		case 'P':
			_path_defpath = optarg;
			break;
		case 'z':
			/*
			 * for comaptability with SSLtelnet
			 */
			if (OPTARG_VAL(optarg, cp, "cert"))
				cert_file = cp;
			else if (OPTARG_VAL(optarg, cp, "cipher"))
				cipher_list = cp;
			else if (OPTARG_VAL(optarg, cp, "key"))
				key_file = cp;
			else if (OPTARG_VAL(optarg, cp, "verify"))
				verify_flag = atoi(cp);
			else if (OPTARG_VAL(optarg, cp, "auth"))
                                _path_ssl_users = cp;
			break;
		case 'a':
			check_all = 1;
			break;
		case 'n':
			keepalive = 0;
			break;
		case 'L':
			log_success = 1;
			break;
		case 'p':
			log_fac = optarg;
			break;
		case '?':
		default:
			usage();
			break;
		}

	argc -= optind;
	argv += optind;

	
	openlog(MYNAME, LOG_PID | LOG_ODELAY, logfacs(log_fac));
	
#ifdef DEBUG
	if ((s = inetd_init(port, SOCK_STREAM, 6, &me)) < 0) {
		syslog(LOG_ERR, "inetd_init(%d) failed: %m");
		exit(1);
	} else if (s > 0) {
		for (ch = 0; ch < 3; ch++) {
			if (ch != s) {
				close(ch);
				dup(s);
			}
		}
		if (s >= 3)
			close(s);
		s = 0;
	}
#endif
	/*
	 * some quick sanity checks
	 */
	if (cert_file != 0 && access(cert_file, R_OK) < 0)
		cert_file = 0;
	if (key_file != 0 && access(key_file, R_OK) < 0)
		key_file = 0;
	if (ssld_init(cert_file, key_file, cipher_list, verify_flag, 0) < 0 ||
	    ssl_start(0, LOG_NOTICE, 1) < 0)
		exit(1);
	
	/* we finnish auth later after gathering locuser etc */
	
	fromlen = sizeof (from);
	if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
		syslog(LOG_ERR, "getpeername: %m");
		_exit(1);
	}
	
	if (keepalive &&
	    setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
	    sizeof(on)) < 0)
		syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
	linger.l_onoff = 1;
	linger.l_linger = 60;			/* XXX */
	if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger,
	    sizeof (linger)) < 0)
		syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m");
	doit(&from);
	/* NOTREACHED */
}


int
s_pipe(fds)
	int fds[2];
{
#if defined(SVR4) || defined(__svr4__)
	return(pipe(fds));
#else
	return(socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
#endif
}

char	username[20] = "USER=";
char	homedir[64] = "HOME=";
char	shell[64] = "SHELL=";
char	path[100] = "PATH=";
char	*envinit[] =
	    {homedir, shell, path, username, 0};
char	**environ;

void
doit(fromp)
	struct sockaddr_in *fromp;
{
#ifndef NCARGS
# define NCARGS	0x100000			/* SunOS anyway */
#endif
	struct hostent *hp;
	struct passwd *pwd;
	char *hostname, *errorstr, *errorhost;
	char *cp, sig, buf[BUFSIZ];
	char cmdbuf[NCARGS+1], locuser[16], remuser[16], port2[16];
	char remotehost[2 * MAXHOSTNAMELEN + 1];
	char hostnamebuf[2 * MAXHOSTNAMELEN + 1];
	int master, cc, pid, s, nfd, one = 1;
	int pin[2], pout[2], perr[2];
	u_short port = 0;
	fd_set ready, readfrom, wfds, wready;
	int sslunread, errunread = 0;


	(void) signal(SIGINT, SIG_DFL);
	(void) signal(SIGQUIT, SIG_DFL);
	(void) signal(SIGTERM, SIG_DFL);
#ifdef DEBUG
	{ int t = open(_PATH_TTY, 2);
	  if (t >= 0) {
		ioctl(t, TIOCNOTTY, (char *)0);
		(void) close(t);
	  }
	}
#endif
	fromp->sin_port = ntohs((u_short)fromp->sin_port);
	if (fromp->sin_family != AF_INET) {
		syslog(LOG_ERR, "malformed \"from\" address (af %d)\n",
		    fromp->sin_family);
		exit(1);
	}
#ifdef IP_OPTIONS
      {
	u_char optbuf[BUFSIZ/3], *cp;
	char lbuf[BUFSIZ], *lp;
	int optsize = sizeof(optbuf), ipproto;
	struct protoent *ip;

	if ((ip = getprotobyname("ip")) != NULL)
		ipproto = ip->p_proto;
	else
		ipproto = IPPROTO_IP;
	if (!getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf, &optsize) &&
	    optsize != 0) {
		lp = lbuf;
		for (cp = optbuf; optsize > 0; cp++, optsize--, lp += 3)
			sprintf(lp, " %2.2x", *cp);
		syslog(LOG_NOTICE,
		    "Connection received from %s using IP options (ignored):%s",
		    inet_ntoa(fromp->sin_addr), lbuf);
		if (setsockopt(0, ipproto, IP_OPTIONS,
		    (char *)NULL, optsize) != 0) {
			syslog(LOG_ERR, "setsockopt IP_OPTIONS NULL: %m");
			exit(1);
		}
	}
      }
#endif
	errorstr = NULL;
	hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof (struct in_addr),
		fromp->sin_family);
	if (hp) {
		/*
		 * If name returned by gethostbyaddr is in our domain,
		 * attempt to verify that we haven't been fooled by someone
		 * in a remote net; look up the name and check that this
		 * address corresponds to the name.
		 */
		hostname = hp->h_name;
		if (check_all || local_domain(hp->h_name)) {
			strncpy(remotehost, hp->h_name, sizeof(remotehost) - 1);
			remotehost[sizeof(remotehost) - 1] = 0;
			errorhost = remotehost;
			hp = gethostbyname(remotehost);
			if (hp == NULL) {
				syslog(LOG_INFO,
				    "Couldn't look up address for %s",
				    remotehost);
				errorstr =
				"Couldn't look up address for your host (%s)\n";
				hostname = inet_ntoa(fromp->sin_addr);
			} else for (; ; hp->h_addr_list++) {
				if (hp->h_addr_list[0] == NULL) {
					syslog(LOG_NOTICE,
					  "Host addr %s not listed for host %s",
					    inet_ntoa(fromp->sin_addr),
					    hp->h_name);
					errorstr =
					    "Host address mismatch for %s\n";
					hostname = inet_ntoa(fromp->sin_addr);
					break;
				}
				if (!bcmp(hp->h_addr_list[0],
				    (caddr_t)&fromp->sin_addr,
				    sizeof(fromp->sin_addr))) {
					hostname = hp->h_name;
					break;
				}
			}
		}
		hostname = strncpy(hostnamebuf, hostname,
				   sizeof(hostnamebuf) - 1);
	} else
		errorhost = hostname = strncpy(hostnamebuf,
					       inet_ntoa(fromp->sin_addr),
					       sizeof(hostnamebuf) - 1);

	hostnamebuf[sizeof(hostnamebuf) - 1] = '\0';

	alarm(60);
	getstr(port2, sizeof(port2), "port2");
	alarm(0);
	port = atoi(port2);

	if (port != 0) {
		/*
		 * Note: we do not use reserved ports
		 */
		fromp->sin_port = htons(port);
		if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0 ||
		    connect(s, (struct sockaddr *)fromp, sizeof (*fromp)) < 0) {
			syslog(LOG_INFO, "connect second port %d: %m", port);
			exit(1);
		}
		if (ssl_start2(s, LOG_NOTICE, 1) < 0)
			exit(1);
	}
	
	getstr(remuser, sizeof(remuser), "remuser");
	getstr(locuser, sizeof(locuser), "locuser");
	getstr(cmdbuf, sizeof(cmdbuf), "command");
	
	setpwent();
	pwd = getpwnam(locuser);
	if (pwd == NULL) {
		syslog(LOG_NOTICE|LOG_AUTH,
		    "%s@%s as %s: unknown login. cmd='%.80s'",
		    remuser, hostname, locuser, cmdbuf);
		if (errorstr == NULL)
			errorstr = "Login incorrect.\n";
		goto fail;
	}
	/*
	 * <sjg> we chroot() first, so that we can have say:
	 * /chroot/users/fred and not necessarily need to replicate
	 * everything for each chroot user.
	 */
	(void) rsh_chroot(pwd);
	if (chdir(pwd->pw_dir) < 0) {
		(void) chdir("/");
#ifdef notdef
		syslog(LOG_NOTICE|LOG_AUTH,
		    "%s@%s as %s: no home directory. cmd='%.80s'",
		    remuser, hostname, locuser, cmdbuf);
		error("No remote directory.\n");
		exit(1);
#endif
	}

	if (errorstr != NULL ||
	    (pwd->pw_passwd != 0 && *pwd->pw_passwd != '\0' &&
	    ssld_auth(hostname, remuser, locuser) <= 0)) {
		if (errorstr) {
			/*
			 * ssld_auth() not called, if it were it would
			 * have logged this...
			 */
			syslog(LOG_NOTICE|LOG_AUTH,
			       "%s@%s as %s: permission denied. cmd='%.80s'",
			       remuser, hostname, locuser, cmdbuf);
			syslog(LOG_DEBUG, "errorstr(%lx) = '%s', hostname(%lx) = '%s', errorhost(%lx) = '%s'",
			       errorstr,errorstr,
			       hostname,hostname,
			       errorhost,errorhost);
		}
fail:
		if (errorstr == NULL)
			errorstr = "Permission denied.\n";
		error(errorstr, errorhost);
		exit(1);
	}

	if (pwd->pw_uid && !access(_PATH_NOLOGIN, F_OK)) {
		error("Logins currently disabled.\n");
		exit(1);
	}

	(void) write_net(0, "\0", 1);
	sent_null = 1;

	if (*pwd->pw_shell == '\0' || !use_user_shell)
		pwd->pw_shell = _PATH_BSHELL;
#if	BSD > 43
	if (setlogin(pwd->pw_name) < 0)
		syslog(LOG_ERR, "setlogin() failed: %m");
#endif
	(void) setgid((gid_t)pwd->pw_gid);
	initgroups(pwd->pw_name, pwd->pw_gid);
	(void) setuid((uid_t)pwd->pw_uid);
	environ = envinit;
	strncat(homedir, pwd->pw_dir, sizeof(homedir)-6);
	strncat(path, _path_defpath, sizeof(path)-6);
	strncat(shell, pwd->pw_shell, sizeof(shell)-7);
	strncat(username, pwd->pw_name, sizeof(username)-6);
	endpwent();

	if (log_success || pwd->pw_uid == 0) {
		    syslog(LOG_NOTICE|LOG_AUTH, "%s@%s as %s: cmd='%.80s'",
			remuser, hostname, locuser, cmdbuf);
	}

	/*
	 * On 4.4BSD we can use a socketpair() always, but just about
	 * everything else gets that wrong, so if port != 0, we use a
	 * few pipes instead.
	 */
#if !defined(BSD4_4) && !defined(SHUTDOWN_SOCKETPAIR_WORKS) && !defined(USE_SOCKETPAIR_ALWAYS)
	if (port == 0)
#endif
		use_socketpair = 1;

	if (use_socketpair) {
		if (s_pipe(pin) < 0) {
			error("Can't make pipe.\n");
			exit(1);
		}
	} else {
		if (pipe(pin) < 0 ||
		    pipe(pout) < 0) {
			error("Can't make pipe.\n");
			exit(1);
		}
	}
	if (port != 0 && pipe(perr) < 0) {
		error("Can't make pipe.\n");
		exit(1);
	} 
	pid = fork();
	if (pid < 0) {
		error("Can't fork; try again.\n");
		exit(1);
	}
	if (pid) {
		(void) close(1);
		(void) close(2);
		(void) close(pin[0]);
		if (use_socketpair)
			pout[0] = pin[1];
		else
			(void) close(pout[1]);
		if (port)
			(void) close(perr[1]);

		FD_ZERO(&readfrom);
		FD_SET(0, &readfrom);
		FD_SET(pout[0], &readfrom);
#if 0						/* no! */
		fcntl(0, F_SETFL, O_NDELAY);
		fcntl(pout[0], F_SETFL, O_NDELAY);
#endif
		if (port) {
			FD_SET(s, &readfrom);
			FD_SET(perr[0], &readfrom);
#if 0						/* no! */
			fcntl(perr[0], F_SETFL, O_NDELAY);
			fcntl(s, F_SETFL, O_NDELAY);
#endif
		}

		/* REVISIT: should we set s,0 and pin[0] nbio? */
		nfd = 16;
		do {
			/*
			 * we need to avoid calling select() if we have
			 * unprocessed data within SSL
			 */
			sslunread = ssl_pending(0);
			if (port)
				errunread = ssl_pending(s);
			
			if ((sslunread | errunread) == 0) {
				ready = readfrom;
				if (select(nfd, &ready, (fd_set *)0,
					   (fd_set *)0, (struct timeval *)0) < 0)
					break;
			}
			if (sslunread ||
			    FD_ISSET(0, &ready)) { /* net */
				errno = 0;
				cc = read_net(0, buf, sizeof(buf));
				if (cc <= 0) {
					if (use_socketpair) {
#ifdef SHUTOWN_HACK
						/*
						 * A total crok, but it
						 * could be an old ssl_rcmd()
						 */
						if (strcmp(cmdbuf, pwd->pw_shell) == 0 ||
						    strcmp(cmdbuf, _PATH_BSHELL) == 0) {
							(void)write(pin[1], "\nexit\n", 6); /* truely ugly */
						} else {
							alarm(60);
						}
#endif
						shutdown(pin[1], 1);

					} else
						close(pin[1]);
					FD_CLR(0, &readfrom);
				} else {
					(void) write_net(pin[1], buf, cc);
				}
			}
			if (FD_ISSET(pout[0], &ready)) { /* child stdout */
				errno = 0;
				cc = read(pout[0], buf, sizeof(buf));
				if (cc <= 0) {
					shutdown(0, 1+1);
					FD_CLR(pout[0], &readfrom);
				} else {
					(void) write_net(0, buf, cc);
				}
			}
			if (port) {
				if (errunread ||
				    FD_ISSET(s, &ready)) { /* signal */
					errno = 0;
					cc = read_net(s, &sig, 1);
					if (cc <= 0)
						FD_CLR(s, &readfrom);
					else
						killpg(pid, sig);
				}
				if (FD_ISSET(perr[0], &ready)) { /* stderr */
					errno = 0;
					cc = read(perr[0], buf, sizeof(buf));
					if (cc <= 0) {
						shutdown(s, 1+1);
						FD_CLR(perr[0], &readfrom);
					} else {
						(void) write_net(s, buf, cc);
					}
				}
			}

		} while ((port != 0 && (FD_ISSET(s, &readfrom) ||
					FD_ISSET(perr[0], &readfrom))) ||
			 FD_ISSET(0, &readfrom) ||
			 FD_ISSET(pout[0], &readfrom)
			 );
		exit(0);
	}
#ifdef HAVE_SETSID
	setsid();
#else
#if defined(__svr4__) || defined(SYSV) || defined(SETPGRP_VOID)
	setpgrp();
#else
	setpgrp(0, getpid());
#endif
#endif
	(void) close(0);
	(void) close(pin[1]);
	dup2(pin[0], 0);
	close(pin[0]);
	(void) close(1);
	if (use_socketpair)
		dup2(0, 1);
	else {
		(void) close(pout[0]);
		dup2(pout[1], 1);
		close(pout[1]);
	}
	(void) close(2);
	if (port) {
		(void) close(s);
		(void) close(perr[0]);
		dup2(perr[1], 2);
		close(perr[1]);
	} else {
		dup2(1, 2);
	}

	/*
	 * <sjg> try to save at least one useless process
	 */
	if (strcmp(cmdbuf, pwd->pw_shell) == 0 ||
	    strcmp(cmdbuf, _PATH_BSHELL) == 0) {
		cp = strrchr(cmdbuf, '/');
		if (cp)
			cp++;
		else
			cp = cmdbuf;
		pwd->pw_shell = cmdbuf;
	} else {
		cp = strrchr(pwd->pw_shell, '/');
		if (cp)
			cp++;
		else
			cp = pwd->pw_shell;
	}
	if (pwd->pw_shell == cmdbuf) {
		execl(cmdbuf, cp, 0);
		perror(cmdbuf);
	} else {
		execl(pwd->pw_shell, cp, "-c", cmdbuf, 0);
		perror(pwd->pw_shell);
	}
	exit(1);
}

/*
 * Report error to client.  Note: can't be used until second socket has
 * connected to client, or older clients will hang waiting for that
 * connection first.
 */
#if __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif

void
#if __STDC__
error(const char *fmt, ...)
#else
error(fmt, va_alist)
	char *fmt;
        va_dcl
#endif
{
	va_list ap;
	int len;
	char *bp, buf[BUFSIZ];
#if __STDC__
	va_start(ap, fmt);
#else
	va_start(ap);
#endif
	bp = buf;
	if (sent_null == 0) {
		*bp++ = 1;
		len = 1;
	} else
		len = 0;
#if defined(BSD4_4) || defined(HAVE_VSNPRINTF)
	(void)vsnprintf(bp, sizeof(buf) - 1, fmt, ap);
#else
	(void)vsprintf(bp, fmt, ap);		/* risky */
#endif
	(void)write_net(0, buf, len + strlen(bp));
}

void
getstr(buf, cnt, err)
	char *buf, *err;
	int cnt;
{
	char c;

	do {
		if (read_net(STDIN_FILENO, &c, 1) != 1)
			exit(1);
		*buf++ = c;
		if (--cnt == 0) {
			error("%s too long\n", err);
			exit(1);
		}
	} while (c != 0);
}

/*
 * Check whether host h is in our local domain,
 * defined as sharing the last two components of the domain part,
 * or the entire domain part if the local domain has only one component.
 * If either name is unqualified (contains no '.'),
 * assume that the host is local, as it will be
 * interpreted as such.
 */
int
local_domain(h)
	char *h;
{
	char localhost[MAXHOSTNAMELEN];
	char *p1, *p2;

	localhost[0] = 0;
	(void) gethostname(localhost, sizeof(localhost));
	p1 = topdomain(localhost);
	p2 = topdomain(h);
	if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2))
		return (1);
	return (0);
}

char *
topdomain(h)
	char *h;
{
	char *p, *maybe = NULL;
	int dots = 0;

	for (p = h + strlen(h); p >= h; p--) {
		if (*p == '.') {
			if (++dots == 2)
				return (p);
			maybe = p;
		}
	}
	return (maybe);
}

void
usage()
{

	syslog(LOG_ERR, "usage: %s [-%s]", MYNAME, OPTIONS);
	exit(2);
}
