#ifndef lint
static char *sccsid = "@(#)rwho.c	1.2 (UKC) 18/11/87";
#endif  lint
/***

* program name:
	rwho.c
* usage:
	rwho hostname [hostname]..
* function:
	Print who is on the named system(s)
* libraries used:
	-ltsb		Transport service primitives
* history:
	Converted to C frmo a shell script by Z.Z.K. Johannes, UKC
* author:
	Copyright by Martin Guy, University of Kent, 1987

***/

#include <stdio.h>
#include <pwd.h>
#include <sys/wait.h>

char *getlogin();
char *ttyname();
char *rindex();
struct passwd *getpwuid();

static char *progname;	/* argv[0] for error reporting */

main(argc,argv)
	int	argc;
	char	*argv[];

{
	int	n;
	char	rwhod[256];
	char	explan[256];		/* explan field of conenct message
					 * encodes who is using rwho */
	union wait childstat;
	char	*tty, *newtty;		/* pointer to "tty31" of user */
	char	*login;			/* of person running rwho */

	progname = argv[0];

	if (argc<2) {
		fprintf(stderr,"Usage: %s hostname [hostname] ...\n", progname);
		exit(1);
	}

	for (n=1;n<argc;n++) {

		/* constrict daemon's TS address */
		(void) sprintf(rwhod,"%s/srv/rwhod",argv[n]);

		/*
		 *	Put who is calling in the explanatory text field
		 */

		/* get tty name and strip back to the base name */
		tty = ttyname(0);
		if (tty != NULL && (newtty = rindex(tty, '/')) != NULL) {
			tty = newtty + 1;	/* just to the right of the / */
		}

		/* find out who they really are as best we can */
		if ((login = getlogin()) == NULL) {
			login = getpwuid(getuid())->pw_name;
		}

		(void) sprintf(explan, "%s,%s", login, tty);


		switch  (vfork()) {
		case -1:		/* Failure */
			fprintf(stderr, "%s: ", progname);
			perror("Cannot fork");
			exit(1);

		case 0:			/* Child */
			execl("/usr/local/connect","connect","-t10","-i",
				"-e", explan,
				rwhod, (char *)0);
			/* Urgle! writing to parent's data in a vfork!
			 * Should be ok, as stderr is flushed.
			 * Let's just cross our fingers and hope...
			 */
			perror("Cannot execute /usr/local/connect");
			fflush(stderr);
			/* tell parent to give up */
			exit(100);	/* connect only returns 0 or 1 */

		default:		/* Parent */
			wait(&childstat);
			if(childstat.w_status==100) exit(1);
			/* if connect failed, it will have printed a message */
			/*
			 * Special case: observed several cases of rwho to VMS
			 * producing an unkillable process with a tsb port open.
			 *
			 * May as well include the other non-unix UKC  machines
			 * as people are likely to try them.
			 */
			if (childstat.w_status != 0 && (
			       strcmp(argv[n], "saturn") == 0
			    || strcmp(argv[n], "janus") == 0
			    || strcmp(argv[n], "titan") == 0
			    || strcmp(argv[n], "gate") == 0
			    || strcmp(argv[n], "sgate") == 0
			    ) ) {
				fprintf(stderr, "%s: rwho does not work to non-unix machines.\n", progname);
			}

		}
	}
	exit(0);		/* Finished */
}
