/*
 * $Id: c1783b58c5e4216be2996dad8d26eaa3be793fc4 $
 *
 * This file is part of nsmtp.
 *
 * Copyright (c) 2007, 2008 Niklas Olmes <niklas@noxa.de>
 *                          http://www.nevm.de/nsmtp/
 *                          NEVM-RIPE
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2
 * as published by the Free Software Foundation.
 *
 * 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

#include "log.h"
#include "cidr.h"

static const char rcsid[] = "$Id: c1783b58c5e4216be2996dad8d26eaa3be793fc4 $";

int
cidr_ip_in_net(const char *ip, const char *net)
{
	struct in_addr ne, ad;
	uint32_t network, netmask, address;
	char buf[32];
	char *p;
	int prefix;
	int i;

	if (inet_aton(ip, &ad) == 0) {
		xinfo("info: cidr_ip_in_net() => invalid ip address [%s]", ip);
		return -1;
	}
	address = ntohl(ad.s_addr);

	prefix = 32;
	(void)snprintf(buf, sizeof(buf), "%s", net);
	if ((p = strchr(buf, '/')) != NULL) {
		*p = '\0';
		++p;
		prefix = atoi(p);
		if (prefix < 0 || prefix > 32) {
			xinfo("info: cidr_ip_in_net() => invalid prefix in net <%s>", net);
			return -1;
		}
	}
	netmask = 0;
	if (prefix > 0)
		netmask = 0xffffffff << (32 - prefix);

	if (inet_aton(buf, &ne) == 0) {
		xinfo("info: cidr_ip_in_net() => invalid network address [%s]", buf);
		return -1;
	}
	network = ntohl(ne.s_addr);

	for (i = 0; i < 32; i++)
		if (netmask << i && ((network << i >> 31) != (address << i >> 31)))
			return 0;

	return 1;
}
