/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/




#include	<errno.h>
#include	<stdio.h>
#include	<sys/types.h>
#include	"netutils.h"
#include	"resolve.h"
#include	"utils.h"
#include	"memory_debug.h"

#define HOSTENT_HASH_SIZE 20
struct hostent * hostent_hash[HOSTENT_HASH_SIZE];
int hf_cnt;


void
init_resolv()
{
int i;
	for ( i = 0;  i < HOSTENT_HASH_SIZE;  i++ ) {
		hostent_hash[i] = 0;
	}
	hf_cnt= 0;
}

struct hostent *
get_new_hostent()
{
struct hostent * ret;
	ret = (struct hostent *)d_alloc(sizeof(struct hostent));
	ret->h_aliases[0] = 0;
	ret->h_addrtype = AF_INET;
	ret->h_length = 4;
	ret->next = NULL;

	return ret;
}

int
hostent_hash_key(int len, char *address)
{
int i, key = 0;
	for ( i = 0;  i < len;  i++ )
		key += (unsigned char)address[i];
	return key % HOSTENT_HASH_SIZE;
}

struct hostent *
search_hostent_hash(int len, char *address)
{
struct hostent * he;
int key = hostent_hash_key(len,address);
	for ( he = hostent_hash[key] ; he ; he = he->next )
		if ( he->h_length == len && memcmp(he->h_addr_list[0], address, len) == 0 )
			return he;
	return NULL;
}

void
add_to_hostent_hash(struct hostent *he)
{
int key = hostent_hash_key(he->h_length,he->h_addr_list[0]);
	printf("new hostent %s(%d)\n",he->h_name,key);
	he->next = hostent_hash[key];
	hostent_hash[key] = he;
}


int
name_entry_size(struct hostent * he)
{
	return 1;
}

int
addr_entry_size(struct hostent * he)
{
	return 1;
}


HOST_ENTRY *
machine2he_v4(struct hostent * he)
{
HOST_ENTRY * ret;
int i;
char ** q;
	if ( he == 0 )
		return 0;
	ret = new_host_entry(
		name_entry_size(he),
		addr_entry_size(he));
	ret->canonical = ret->names[0] = copy_str(he->h_name);
	for ( i = 1 , q = he->h_aliases ; *q ; q ++ , i ++ )
		ret->names[i] = copy_str(*q);
	ret->names[i] = 0;
	for ( i = 0; i < ret->ips_length ; i ++ ) {
		ret->ips[i].type = HAT_V4;
		ret->ips[i].size = sizeof(int);
		ret->ips[i].d.v4 = ntohl(*(unsigned int*)he->h_addr_list[i]);
	}
	for ( i = 0 ; ret->names[i] ; i ++ )
		if ( strcmp(ret->names[i],"loghost") == 0 )
			ret->flags |= HEF_LOGHOST;
	return ret;
}


