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

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

/*
 *  Cookie -  Quote-of-the-day (or "fortune cookie") client
 */

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

#define	TIMEOUT 5
#define	RETRYCOUNT 3

int 	timeout();

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

	if (argc != 2){
		fprintf(stderr, "usage: cookie host\n");
		exit(1);
	}
	ret_val = netfortune(argv[1]);
	exit(ret_val);
}

char buf[512];

netfortune(host)
	char *host;
{
	struct hostent *hp;
	struct servent *sp;
	struct sockaddr_in sin;
	int s;
	int cc;
	int fromlen = sizeof(sin);
	int i;

	hp = gethostbyname(host);
	if (hp == NULL) {
		static struct hostent server;
		static struct in_addr serveraddr;
		static char *address_list[1];
		unsigned long inet_addr();

		serveraddr.s_addr = inet_addr(host);
		if (serveraddr.s_addr == -1) {
			fprintf(stderr, "unknown host: %s\n", host);
			return (1);
		}
		server.h_name = host;
		server.h_addr_list = address_list;
		server.h_addr = (char *)&serveraddr;
		server.h_length = sizeof (struct in_addr);
		server.h_addrtype = AF_INET;
		server.h_aliases = 0;
		hp = &server;
	}
	printf("[%s]\n", hp->h_name);
	sp = getservbyname("qotd", "udp");
	if (sp == 0) {
		fprintf(stderr, "udp/qotd: unknown service\n");
		return (1);
	}
	sin.sin_family = hp->h_addrtype;
	bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
	sin.sin_port = sp->s_port;
	s = socket(hp->h_addrtype, SOCK_DGRAM, 0);
	if (s < 0) {
		perror("creating datagram socket");
		return (1);
	}
	signal(SIGALRM, timeout);
	for (i = 0; i < RETRYCOUNT; i++){
		cc = sendto(s, host, sizeof(host), 0, (struct sockaddr *) &sin,
		  sizeof(sin));
		if (cc < 0) {
			perror("sending datagram message");
			continue;
		}
		alarm(TIMEOUT);
		/*  make sure buf doesn't lose it's terminating '\0' */
		cc = recvfrom(s, buf, sizeof(buf) - 1, 0, (struct sockaddr *)
		  &sin, &fromlen);
		if (cc > 0){
			break;
		}
	}
	if (cc < 0){
		fprintf(stderr, "cookie: no response from %s\n", host);
		close (s);
		return (1);
	}
	printf("%s", buf);
	close (s);
	return(0);
}

timeout()
{
	/*
	 *  just return -  the only reason for the interrupt is
	 *  to interrupt the recvfrom system call
	 */
}
