/*
	Auther	Satoshi Yasuda	7m3tjz/ad6gz
*/

#include	"trustDB.h"
char	*FindRepeater(char repeater[]);
void	UpdateRepeater(struct   shm_form  recv_msg);

void CheckEntry(void)
{
	int	ret;
	int	len;
	socklen_t addrlen;
	char	repeater[8];

	addrlen = sizeof(struct sockaddr_in);
	ret = recvfrom(TrustDB_out, &RelayPacket, sizeof(RelayPacket), 0, 
		(struct sockaddr *)&db_out, &addrlen);
	if (ret > 0)
	{
		if (memcmp ((char *)&RelayPacket.dv.pkt.ID, "DSVT", 4) == 0)	/* Relay Mode */
		{
                        memset((char *)&db_in,0,sizeof(db_in));
                        db_in.sin_family = PF_INET;
                        db_in.sin_port = RelayPacket.dv.port;
                        db_in.sin_addr = RelayPacket.dv.ip;
			len = 27;
			if (RelayPacket.dv.pkt.B_header.seq == 0x80) len = 56;	/* header */
                        sendto (TrustDB_out, &RelayPacket.dv.pkt, len, 0,
                                (struct sockaddr *)&db_in, sizeof(db_in));
		}
		else if (RelayPacket.send_msg.type == RepActive)
		{
			StoreRepeater (RelayPacket.send_msg.rep_name, RelayPacket.send_msg.trust_name);
		}
		else
		{
        		memset((char *)&db_in,0,sizeof(db_in));
        		db_in.sin_family = PF_INET;
        		db_in.sin_port = dbInPort;
        		db_in.sin_addr = dbIP;
			RelayPacket.send_msg.srcPort = db_out.sin_port;
			RelayPacket.send_msg.srcIP = db_out.sin_addr;
			memcpy (&repeater, &RelayPacket.send_msg.dstCall, 8);
			memcpy (&repeater, FindRepeater(repeater), 8);
			if (repeater[0] != 0x20)
			{
				memcpy (&RelayPacket.send_msg.dstCall, &repeater, 8);
			}
			else
			{
				RelayPacket.send_msg.type = NoRoute;
			}
			sendto (TrustDB_in, &RelayPacket.send_msg, 
				sizeof(struct shm_form), 0, 
				(struct sockaddr *)&db_in, sizeof(db_in));
			if (RelayPacket.send_msg.type == ReqConnect)
				UpdateRepeater(RelayPacket.send_msg);
		}
	}
}

