/*---[ lookup.c ]-----------------------------------------------------
 * Copyright (C) 2000 Tomas Junnonen (majix@sci.fi)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The lookup functions resolve an IP address given in dotted-decimal
 * notation into an hostname
 *--------------------------------------------------------------------*/

#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>

#include "lookup.h"
#include "firestarter.h"

static void error_dialog (void);

extern int h_errno;

/* [ lookup ]
 * Resolve the IP address/hostname from the selected line in hitlogclist
 */
void
lookup (void)
{
	gpointer *clistrow = gtk_object_get_data (GTK_OBJECT (hitlogclist),
						  "row");
	if (clistrow != NULL) {
		static gchar *text;
		gint row = GPOINTER_TO_INT (clistrow);
		gint col = 1;
		struct hostent *answer = NULL;
		struct in_addr address;

		gtk_clist_get_text (GTK_CLIST (hitlogclist), row-1, col, &text);

		if (inet_aton (text, &address)) {
			answer = gethostbyaddr ((char *)&address,
						sizeof (address), AF_INET);
			gtk_object_set_data (GTK_OBJECT (hitlogclist),
					     "ip", g_strdup (text));
		}
		else
			answer = gethostbyname (text);

		if (answer == NULL) {
			error_dialog ();
			return;
		}

		if (answer && inet_aton (text, &address)) {
			gtk_clist_set_text (GTK_CLIST (hitlogclist), row-1, col,
					    answer->h_name);
		}
		else {
			gtk_clist_set_text (GTK_CLIST (hitlogclist), row-1, col,
					    gtk_object_get_data (GTK_OBJECT (hitlogclist),
					    "ip"));
		}
	}
}

static void error_dialog (void)
{
  GtkWidget *lookuperror;

  if (h_errno == HOST_NOT_FOUND)
	lookuperror = gnome_error_dialog (_("Host not found."));
  else if (h_errno == NO_ADDRESS || h_errno == NO_DATA)
	lookuperror = gnome_error_dialog (_("The host is valid but does not have an IP address."));
  else if (h_errno == NO_RECOVERY)
	lookuperror = gnome_error_dialog (_("Non recovery error in the DNS server."));
  else
	lookuperror = gnome_error_dialog (_("There was a problem with the DNS server. Please try again."));

  gtk_widget_show (lookuperror);
}
