/*---[ lookup.h ]-----------------------------------------------------
 * 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
 *
 * Based on firestarter code by Tomas Junnonen (majix@sci.fi)
 *--------------------------------------------------------------------*/

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

#include "lookup.h"
#include "razorback.h"

/* [ 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;
		char result[512];
		char ip1[256],port1[25],ip2[256],port2[25];
		gint row = GPOINTER_TO_INT (clistrow);
		gint col = 2;
		char * position, *position2;
		struct hostent *answer = NULL;
		struct in_addr address;
		struct in_addr address2;

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

		position=strstr(text,":");
		strncpy(ip1,text,(position-text));
		ip1[position-text]='\0';
		position2=strstr(text," -> ");
		position+=sizeof(char);
		strncpy(port1,position,position2-position);
		port1[position2-position]='\0';

		position=position2+sizeof(char)*4;
		position2=strstr(position,":");
		strncpy(ip2,position,position2-position);
		ip2[position2-position]='\0';

		position2+=sizeof(char);
		strcpy(port2,position2);

		if (inet_aton (ip1, &address)) {
			answer = gethostbyaddr ((char *)&address,sizeof(address),AF_INET);
			if(answer) {
				strcpy(ip1,answer->h_name);
			}
		}
		if (inet_aton (ip2, &address)) {
			answer = gethostbyaddr ((char *)&address,sizeof(address),AF_INET);
			if(answer) {
				strcpy(ip2,answer->h_name);
			}
		}
		sprintf(result,"%s:%s -> %s:%s",ip1,port1,ip2,port2);

		gtk_clist_set_text (GTK_CLIST (hitlogclist), row-1, col,
				    result);
	}
}
