/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1988
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* $Header:fortuned.c 12.0$ */
/* $ACIS:fortuned.c 12.0$ */
/* $Source: /ibm/acis/usr/src/ibm/fortuned/RCS/fortuned.c,v $ */

#ifndef lint
static char *rcsid = "$Header:fortuned.c 12.0$";
#endif

/*
 *  Fortune demon -  Quote-of-the-day (or "fortune cookie") server
 */

#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>


char buf[1024];

main(argc, argv)
	char *argv[];
{
	struct sockaddr_in from;
	int fromlen;
	int n;
	int p[2];
	int pid;
	char *av[2];
	FILE *fp;
	int j;
	int c;
	union wait status;
	int i;

	fromlen = sizeof(from);
	n = recvfrom(0, buf, sizeof (buf), 0, (struct sockaddr *)
		&from, &fromlen);
	if (n < 0) 
		fatal(argv[0], "recvfrom");
	if (pipe(p) < 0)
		fatal(argv[0], "pipe");
	if ((pid = fork()) == 0) {
		close(p[0]);
		if (p[1] != 1) {
			dup2(p[1], 1);
			close(p[1]);
		}
		av[0] = "fortune";
		av[1] = 0;
		execv("/usr/games/fortune", av);
		_exit(1);
	}
	if (pid == -1)
		fatal(argv[0], "fork");
	close(p[1]);
	if ((fp = fdopen(p[0], "r")) == NULL)
		fatal(argv[0], "fdopen");
	j = 0;
#define bump(j)  if (++j >= sizeof(buf))  break;
	while ((c = getc(fp)) != EOF) {
		buf[j] = c;
		if (buf[j] == '\n') {
			buf[j] = '\r';
			bump(j);
			buf[j]='\n';
		}
		bump(j);
	}
#undef bump
	if (sendto(0, buf, j, 0, (struct sockaddr *) &from, sizeof (from)) < 0)
		fatal(argv[0],"sending datagram");
	fclose(fp);
	while ((i = wait(&status)) != pid && i != -1)
		;
	return(0);
}

fatal(prog, s)
	char *prog, *s;
{
	fprintf(stderr, "%s: ", prog);
	perror(s);
	exit(1);
}
