/*-
 * Copyright (c) 1983, 1990 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.
 */

#include "bsd_locl.h"

RCSID("$Header: /afs/nada.kth.se/src/packages/kth-krb/SourceRepository/krb4/appl/bsd/rsh.c,v 1.8 1995/10/26 11:49:00 bg Exp $");

#include <sys/ioctl.h>

CREDENTIALS cred;
Key_schedule schedule;
int use_kerberos = 1, doencrypt;
char dst_realm_buf[REALM_SZ], *dest_realm;

/*
 * rsh - remote shell
 */
int rfd2;

static void
usage(void)
{
	(void)fprintf(stderr,
	    "usage: rsh [-nd%s]%s[-l login] host [command]\n",
	    "x", " [-k realm] ");
	exit(1);
}

static void
warning(const char *fmt, const char *arg)
{
    char *rstar_no_warn = getenv("RSTAR_NO_WARN");
    if (rstar_no_warn == 0)
	rstar_no_warn = "";
    if (strncmp(rstar_no_warn, "yes", 3) != 0) {
	(void)fprintf(stderr, "rsh: warning, using standard rsh: ");
	fprintf(stderr, fmt, arg);
	(void)fprintf(stderr, ".\n");
    }
}

static char *
copyargs(char **argv)
{
	register int cc;
	register char **ap, *p;
	char *args;

	cc = 0;
	for (ap = argv; *ap; ++ap)
		cc += strlen(*ap) + 1;
	if (!(args = malloc((u_int)cc))) {
		(void)fprintf(stderr, "rsh: %s.\n", k_strerror(ENOMEM));
		exit(1);
	}
	for (p = args, ap = argv; *ap; ++ap) {
		(void)strcpy(p, *ap);
		for (p = strcpy(p, *ap); *p; ++p);
		if (ap[1])
			*p++ = ' ';
	}
	return(args);
}

static RETSIGTYPE
sendsig(int signo_)
{
  unsigned char signo = signo_;
	if (doencrypt)
#ifdef NOENCRYPTION
		(void)write(rfd2, &signo, 1);
#else
		(void)des_enc_write(rfd2, &signo, 1, schedule, &cred.session);
#endif
	else
		(void)write(rfd2, &signo, 1);
}

static void
talk(int nflag, sigset_t omask, int pid, register int rem)
{
	register int cc, wc;
	register char *bp;
	fd_set readfrom, ready, rembits;
	char buf[BUFSIZ];

	if (pid == 0) {
		if (nflag)
			goto done;

		(void)close(rfd2);

reread:		errno = 0;
		if ((cc = read(0, buf, sizeof buf)) <= 0)
			goto done;
		bp = buf;

rewrite:	FD_ZERO(&rembits);
		FD_SET(rem, &rembits);
		if (select(16, 0, &rembits, 0, 0) < 0) {
			if (errno != EINTR) {
				(void)fprintf(stderr,
				    "rsh: select: %s.\n", k_strerror(errno));
				exit(1);
			}
			goto rewrite;
		}
		if (!FD_ISSET(rem, &rembits))
			goto rewrite;
		if (doencrypt)
#ifdef NOENCRYPTION
			wc = write(rem, bp, cc);
#else
			wc = des_enc_write(rem, bp, cc, schedule, &cred.session);
#endif
		else
			wc = write(rem, bp, cc);
		if (wc < 0) {
			if (errno == EWOULDBLOCK)
				goto rewrite;
			goto done;
		}
		bp += wc;
		cc -= wc;
		if (cc == 0)
			goto reread;
		goto rewrite;
done:
		(void)shutdown(rem, 1);
		exit(0);
	}

	if (sigprocmask(SIG_SETMASK, &omask, 0) != 0)
	    perror("sigprocmask");
	FD_ZERO(&readfrom);
	FD_SET(rem, &readfrom);
	FD_SET(rfd2, &readfrom);
	do {
		ready = readfrom;
		if (select(16, &ready, 0, 0, 0) < 0) {
			if (errno != EINTR) {
				(void)fprintf(stderr,
				    "rsh: select: %s.\n", k_strerror(errno));
				exit(1);
			}
			continue;
		}
		if (FD_ISSET(rfd2, &ready)) {
			errno = 0;
			if (doencrypt)
#ifdef NOENCRYPTION
				cc = read(rfd2, buf, sizeof buf);
#else
				cc = des_enc_read(rfd2, buf, sizeof buf, schedule, &cred.session);
#endif
			else
				cc = read(rfd2, buf, sizeof buf);
			if (cc <= 0) {
				if (errno != EWOULDBLOCK)
					FD_CLR(rfd2, &readfrom);
			} else
				(void)write(2, buf, cc);
		}
		if (FD_ISSET(rem, &ready)) {
			errno = 0;
			if (doencrypt)
#ifdef NOENCRYPTION
				cc = read(rem, buf, sizeof buf);
#else
				cc = des_enc_read(rem, buf, sizeof buf, schedule, &cred.session);
#endif
			else
				cc = read(rem, buf, sizeof buf);
			if (cc <= 0) {
				if (errno != EWOULDBLOCK)
					FD_CLR(rem, &readfrom);
			} else
				(void)write(1, buf, cc);
		}
	} while (FD_ISSET(rfd2, &readfrom) || FD_ISSET(rem, &readfrom));
}

static int get_shell_port(int kerberos, int encryption)
{
  struct servent *sp;
  char *service="shell";
  int port=514;

  if(kerberos && encryption){
    service="ekshell";
    port=2106;
  }
  
  if(kerberos && !encryption){
    service="kshell";
    port=544;
  }
  
  sp=getservbyname(service, "tcp");
  if(sp == NULL){
    fprintf(stderr, "rsh: can't get entry for %s service, using default port %d.\n",
	    service, port);
  }else{
    port=sp->s_port;
  }
  return port;
}

int
main(int argc, char **argv)
{
	struct passwd *pw;
	int sv_port;
	sigset_t omask;
	int argoff, asrsh, ch, dflag, nflag, nfork, one, pid, rem, uid;
	register char *p;
	char *args, *host, *user;

	argoff = asrsh = dflag = nflag = nfork = 0;
	one = 1;
	host = user = NULL;

	/* if called as something other than "rsh", use it as the host name */
	if ((p = strrchr(argv[0], '/')))
		++p;
	else
		p = argv[0];
	if (strcmp(p, "rsh"))
		host = p;
	else
		asrsh = 1;

	/* handle "rsh host flags" */
	if (!host && argc > 2 && argv[1][0] != '-') {
		host = argv[1];
		argoff = 1;
	}

#define	OPTIONS	"8KLdek:l:nwx"
	while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != EOF)
		switch(ch) {
		case 'K':
			use_kerberos = 0;
			break;
		case 'L':	/* -8Lew are ignored to allow rlogin aliases */
		case 'e':
		case 'w':
		case '8':
			break;
		case 'd':
			dflag = 1;
			break;
		case 'l':
			user = optarg;
			break;
		case 'k':
			dest_realm = dst_realm_buf;
			strncpy(dest_realm, optarg, REALM_SZ);
			break;
		case 'n':
			nflag = nfork = 1;
			break;
		case 'x':
			doencrypt = 1;
			break;
		case '?':
		default:
			usage();
		}
	optind += argoff;

	/* if haven't gotten a host yet, do so */
	if (!host && !(host = argv[optind++]))
		usage();

	/* if no further arguments, must have been called as rlogin. */
	if (!argv[optind]) {
		if (asrsh)
			*argv = "rlogin";
		execv(_PATH_RLOGIN, argv);
		(void)fprintf(stderr, "rsh: can't exec %s.\n", _PATH_RLOGIN);
		exit(1);
	}

	argc -= optind;
	argv += optind;

	if (!(pw = getpwuid(uid = getuid()))) {
		(void)fprintf(stderr, "rsh: unknown user id.\n");
		exit(1);
	}
	if (!user)
		user = pw->pw_name;

	/* -n must still fork but does not turn of the -n functionality */
	if (doencrypt)
		nfork = 0;

	args = copyargs(argv);

	sv_port=get_shell_port(use_kerberos, doencrypt);

try_connect:
	if (use_kerberos) {
		rem = KSUCCESS;
		errno = 0;
		if (dest_realm == NULL)
			dest_realm = krb_realmofhost(host);

		if (doencrypt)
			rem = krcmd_mutual(&host, sv_port, user, args,
			    &rfd2, dest_realm, &cred, schedule);
		else
			rem = krcmd(&host, sv_port, user, args, &rfd2,
			    dest_realm);
		if (rem < 0) {
			use_kerberos = 0;
			sv_port=get_shell_port(use_kerberos, doencrypt);
			if (errno == ECONNREFUSED)
			  warning("remote host doesn't support Kerberos", "");
			if (errno == ENOENT)
			  warning("can't provide Kerberos auth data", "");
			goto try_connect;
		}
	} else {
		if (doencrypt) {
			(void)fprintf(stderr,
			    "rsh: the -x flag requires Kerberos authentication.\n");
			exit(1);
		}
		rem = rcmd(&host, sv_port, pw->pw_name, user, args, &rfd2);
	}

	if (rem < 0)
		exit(1);

	if (rfd2 < 0) {
		(void)fprintf(stderr, "rsh: can't establish stderr.\n");
		exit(1);
	}
	if (dflag) {
		if (setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one,
		    sizeof(one)) < 0)
			(void)fprintf(stderr, "rsh: setsockopt: %s.\n",
			    k_strerror(errno));
		if (setsockopt(rfd2, SOL_SOCKET, SO_DEBUG, &one,
		    sizeof(one)) < 0)
			(void)fprintf(stderr, "rsh: setsockopt: %s.\n",
			    k_strerror(errno));
	}

	(void)setuid(uid);
	{
	    sigset_t sigmsk;
	    sigemptyset(&sigmsk);
	    sigaddset(&sigmsk, SIGINT);
	    sigaddset(&sigmsk, SIGQUIT);
	    sigaddset(&sigmsk, SIGTERM);
	    if (sigprocmask(SIG_BLOCK, &sigmsk, &omask) != 0)
	        perror("sigprocmask");
        }
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		(void)signal(SIGINT, sendsig);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		(void)signal(SIGQUIT, sendsig);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		(void)signal(SIGTERM, sendsig);

	if (!nfork) {
		pid = fork();
		if (pid < 0) {
			(void)fprintf(stderr,
			    "rsh: fork: %s.\n", k_strerror(errno));
			exit(1);
		}
	}

	if (!doencrypt)
	{
		(void)ioctl(rfd2, FIONBIO, &one);
		(void)ioctl(rem, FIONBIO, &one);
	}

	talk(nflag, omask, pid, rem);

	if (!nflag)
		(void)kill(pid, SIGKILL);
	exit(0);
}
