/*
 * Copyright (c) 1996-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

#include <stdio.h>
#include <stdlib.h>  
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <signal.h>
#include <unistd.h> 
#include <sys/types.h>
#include <sys/time.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <net/if.h>
#include "firewall.h"
#include "fwfunc.h"

#ifdef IPFILTER
#include "ip_compat.h"
#include "ip_fil.h"
#include "ip_nat.h"
#endif


void
proxy_get_transparent_dst(dsthost,port)
char *dsthost;
unsigned int  *port;
{
	socklen_t		len;
	struct sockaddr_in	to_addr;
#ifdef IPFILTER
	struct sockaddr_in	from_addr;
	int			ipfnat_fd;
	struct	natlookup	natlookup;
#endif

	bzero((char *)&to_addr, sizeof(to_addr));

	len = sizeof(to_addr);
	if (getsockname(0, (struct sockaddr *)&to_addr, &len) < 0) {
		syslog(LLEV,"fwtksyserr: getsockname() failed: %s", strerror(errno));
		exit(1);
	}

#ifndef IPFILTER

	strncpy(dsthost,inet_ntoa(to_addr.sin_addr),sizeof(dsthost));
	return;

#else


	bzero((char *)&from_addr, sizeof(from_addr));
	if (getpeername(0, (struct sockaddr *)&from_addr, &len) < 0) {
		syslog(LLEV,"fwtksyserr: getpeername() failed: %s", strerror(errno));
		exit(1);
	}

	natlookup.nl_inport = to_addr.sin_port;
	natlookup.nl_outport = from_addr.sin_port;
	natlookup.nl_inip = to_addr.sin_addr;
	natlookup.nl_outip = from_addr.sin_addr;
	natlookup.nl_flags = IPN_TCP;

	if ((ipfnat_fd = open(IPL_NAT, O_RDONLY)) < 0) {
		syslog(LLEV,"fwtksyserr: cannot open NAT deivce: %s", strerror(errno));
		exit(1);
	}

	if (ioctl(ipfnat_fd, SIOCGNATL, &natlookup) == -1) {
		syslog(LLEV,"fwtksyserr: SIOCGNATL failed: %s", strerror(errno));
		close(ipfnat_fd);
		exit(1);
	}

	strlcpy(dsthost,inet_ntoa(natlookup.nl_realip),16);
	*port = ntohs(natlookup.nl_realport);
	return;

#endif
}



