#ifndef lint
static char sccsid[] = "@(#)rexboot.c	1.14 (UKC) 3/11/87";
#endif  lint
/* Rexboot
 * This is what replies to the request from another machine for a (say) ditroff.
 * It is kicked off by srv from /etc/ringsrv/{name of program required}
 * with a tsb port connected to file descriptor 0
 * The remotely executing program inherits this.
 *
 * For the moment we will exec the filename we are passed by rpcinit.
 * eventually we will have N links to this program a la games gateway
 * with different names corresponding to the program we are to exec.
 *
 * The REAL rpc-ing binaries are in REXBIN.
 * This is mostly an environment and argument list constructor at the moment.
 */
#include <stdio.h>

#include <sys/time.h>		/* needed by resource.h */
#include <sys/resource.h>	/* for propagating CPU time limit */

#include <sys/tsbsp.h>
#include <sys/tserrno.h>
#include "trans.h"
#include "config.h"

extern char rexversion[];	/* version number string */

#define tsfd 0

static char rexbin[] = REXBIN;
static char logdir[] = LOGDIR;

char *malloc();
char *strcpy();
char *strcat();

main(Argc,Argv)
char **Argv;
{
	register char **argv, **envp;
	char mesg[64];	/* for error messages and making logfile names */
	char name[256];	/* name of program we have to execute */
	struct rlimit rlimit;


#ifdef lint
	Argc = Argc; Argv = Argv;
#endif
	/* Error messages into log files */
	(void) freopen(sprintf(mesg, "%s/rexboot.out", logdir), "w", stdout);
	(void) freopen(sprintf(mesg, "%s/rexboot.err", logdir), "w", stderr);
	setbuf(stdout, (char *) NULL); /* unbuffered */
	setbuf(stderr, (char *) NULL); /* unbuffered */

	/*
	 * Send version number string for rexinit to check.
	 */
	sendstring(tsfd, rexversion, strlen(rexversion) + 1);	/* + null */

	argv = recvvstruct(tsfd);

	envp = recvvstruct(tsfd);

	/*
	 * Receive resource limits for remote troff.
	 * Only cputime at the moment, for batch.
	 */

	rlimit.rlim_cur = recvint(tsfd);
	rlimit.rlim_max = recvint(tsfd);
	if (setrlimit(RLIMIT_CPU, &rlimit) != 0) {
		perror("rexboot: cannot setrlimit");
		exit(1);
	}

	/* Should use Real argument to prevent fraud */
	/* but until I install it properly, exec what we're told our name is */
	(void) sprintf(name, "%s/%s", rexbin, argv[0]);

	execve(name,argv,envp);

#ifdef DEBUG	/* Exec failed; analyse pathname */
	for (i=0; name[i]; i++)
		fprintf(stderr, "%d ", name[i]);
	putc('\n', stderr);
#endif

	rpcfail(tsfd,sprintf(mesg, "%s: Cannot exec \"%s\"\n", Argv[0], name), stderr);
	/* NOTREACHED */
}
