/*
 * dns.c: small utility to provide non blocking DNS resolution
 *
 * Copyright(c) 1997,1998 - All Rights Reserved
 *
 * See the COPYRIGHT file.
 */

#ifndef lint
static char rcsid[] = "@(#)$Id: dns.c,v 1.5 1998/03/03 23:07:02 kalt Exp $";
#endif

#include "os.h"

/* read() */
#include <sys/types.h>
#include <sys/uio.h>
/* gethost* */
#include <netdb.h>
/* inet_* */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/* BIND 8.x lossage */
#undef inet_ntoa
#undef inet_addr

extern	int	h_errno;

void
main()
{
  char	buf[256], reply[300];
  int	rc, i, j = 0;
  FILE	*debug = NULL;

#ifdef DEBUG
  debug = fopen("sdns.log", "a");
#endif
  if (debug)
      fprintf(debug, "Starting: %d\n", (int) getpid());
  while (1)
    {
      /* read the request from stdin */
      i = 0;
      
      buf[0] = '\0';
      while ((rc = read(0, &buf[i], 1)) > 0)
	{
	  if (buf[i++] == '\0')
	      break;
	}
      if (debug)
	  { fprintf(debug, "Got \"%s\" (%d)\n", buf, rc); fflush(debug); }
      if (rc <= 0)
	  exit(rc);

      if (isdigit(buf[0])) /* incorrect but simple */
	{
	  struct hostent *h;
	  unsigned long ad;

	  ad = inet_addr(buf);
	  if (h = gethostbyaddr((char *) &ad, sizeof(ad), AF_INET))
	      sprintf(reply, "%s=%s", buf, h->h_name);
	  else
	      sprintf(reply, "%s:%d", buf, h_errno);
	}
      else
	{
	  struct hostent *h;
	  
	  if (h = gethostbyname(buf))
	      sprintf(reply, "%s=%s", buf, (char *) inet_ntoa(*((struct in_addr *)h->h_addr_list[0])));
	  else
	      sprintf(reply, "%s:%d", buf, h_errno);
	}
      write(1, reply, strlen(reply)+1);

      if (j++>255)
	{
	  if (debug)
	      fprintf(debug, "Exiting.\n");
	  exit(77);
	}
    }
}
