#!/usr/bin/perl -Tw
#
# LMS version 1.7.4 Wraith
#
#  (C) 2001-2005 LMS Developers
#  
#  Please, see the doc/AUTHORS for more information about authors!
#
#  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., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
#  USA.
#
#  $Id: lms-makeiptables,v 1.36 2005/09/22 06:32:58 alec Exp $

use strict;
use DBI;
use Config::IniFiles;
use Getopt::Long;
use vars qw($configfile $quiet $help $version);

sub mask2prefix($)
{
	my $mask = shift @_;
	my @tmp = split('\.',$mask,4);
	my $q = sprintf("%b%b%b%b",$tmp[0],$tmp[1],$tmp[2],$tmp[3]);
	$q =~ s/0*$//;
	if ($q =~ /0/) {
		print " You idiot. error in mask\n";
	}
	my $len = length($q) ;
	return $len;
}

sub matchip($$$)
{
	my ($ip,$net,$mask) = @_;
	my $prefix = mask2prefix($mask);
	my $bmask = 2**32 <<(32-$prefix);
	my @net = split('\.',$net,4);
	my $bnet = dotquad2u32($net);
	if(($bnet & $bmask)!= $bnet) {
		print "EEediot net &mask != net\n"; return 1==0
	}
	my $bip = dotquad2u32($ip);
	return (($bip&$bmask) == $bnet);
}

sub dotquad2u32($)
{
	my $dq = shift||'0.0.0.0';
	my @dq = split('\.',$dq,4);
	return ((($dq[0] << 8) + $dq[1] << 8) + $dq[2] << 8) + $dq[3];
}

sub isprivate($)
{
	my ($ip) = @_;
	return matchip($ip,"192.168.0.0","255.255.0.0") || matchip($ip,"10.0.0.0","255.0.0.0") || matchip($ip,"172.16.0.0","255.240.0.0");
}

my $_version = '1.7.4 Wraith';

my %options = (
	"--config-file|C=s"	=>	\$configfile,
	"--quiet|q"		=>	\$quiet,
	"--help|h"		=>	\$help,
	"--version|v"		=>	\$version
);

Getopt::Long::config("no_ignore_case");
GetOptions(%options);

if($help)
{
	print STDERR <<EOF;
lms-makeiptables, version $_version
(C) 2001-2005 LMS Developers

-C, --config-file=/etc/lms/lms.ini	alternate config file (default: /etc/lms/lms.ini);
-h, --help			print this help and exit;
-v, --version			print version info and exit;
-q, --quiet			suppress any output, except errors;

EOF
	exit 0;
}

if($version)
{
	print STDERR <<EOF;
lms-makeiptables, version $_version
(C) 2001-2005 LMS Developers

EOF
	exit 0;
}

if(!$configfile)
{
	$configfile = "/etc/lms/lms.ini";
}

if(!$quiet)
{
	print STDOUT "lms-makeiptables, version $_version\n";
	print STDOUT "(C) 2001-2005 LMS Developers\n";
	print STDOUT "Using file $configfile as config.\n";
}

if(! -r $configfile)
{
	print STDERR "Fatal error: Unable to read configuration file $configfile, exiting.\n";
	exit 1;
}

my $ini = new Config::IniFiles -file => $configfile;
print @Config::IniFiles::errors;

my $networks_list = $ini->val('iptables', 'networks') || '';
my $forward_to_list = $ini->val('iptables', 'forward_to') || '';
my $cfile = $ini->val('iptables', 'script_file') || '/etc/rc.d/rc.masq';
my $cuid = $ini->val('iptables', 'script_owneruid') || '0';
my $cgid = $ini->val('iptables', 'script_ownergid') || '0';
my $cperm = $ini->val('iptables', 'script_permission') || '700';
my $ipbin = $ini->val('iptables', 'iptables_binary') || '/usr/sbin/iptables';
my $prescript = $ini->val('iptables', 'pre_script') || '';
my $postscript = $ini->val('iptables', 'post_script') || '';
my $snataddr = $ini->val('iptables', 'snat_address') || '';

my $dbtype = $ini->val('database', 'type') || 'mysql';
my $dbhost = $ini->val('database', 'host') || 'localhost';
my $dbuser = $ini->val('database', 'user') || 'root';
my $dbpasswd = $ini->val('database', 'password') || '';
my $dbname = $ini->val('database', 'database') || 'lms';

my $dbase;

if($dbtype eq "mysql")
{
	$dbase = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
}
elsif($dbtype eq "postgres")
{
	$dbase = DBI->connect("DBI:Pg:dbname=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
}
else
{
	print STDERR "Fatal error: unsupported database type: $dbtype, exiting.\n";
	exit 1;
}

open(IPTABLESSCRIPT, ">$cfile") or die("Fatal error: Unable to write $cfile, exiting.\n");

print IPTABLESSCRIPT "#!/bin/bash\n";
print IPTABLESSCRIPT "$ipbin -t nat -F\n";
print IPTABLESSCRIPT "$ipbin -t filter -F\n";
print IPTABLESSCRIPT "$ipbin -P FORWARD DROP\n";

if($prescript)
{
	print IPTABLESSCRIPT "$prescript\n";
}

my $allnetworks = "";

my $dbq = $dbase->prepare("SELECT name FROM networks");
$dbq->execute();
while (my $row = $dbq->fetchrow_hashref()) {
	$allnetworks = "$allnetworks $row->{'name'}";
}

if(!$networks_list)
{
	$networks_list = $allnetworks;
}

if(!$forward_to_list)
{
	$forward_to_list = $allnetworks;
}

my @networks = split ' ',$networks_list;
my @fw_networks = split ' ',$forward_to_list;

foreach my $key (@networks)
{
	my $dbq = $dbase->prepare("SELECT inet_ntoa(address) AS address, mask FROM networks WHERE name = UPPER('$key')");
	$dbq->execute();
	while (my $row = $dbq->fetchrow_hashref()) {
		foreach my $skey (@fw_networks)
		{
			my $sdbq = $dbase->prepare("SELECT inet_ntoa(address) AS address, mask FROM networks WHERE name = UPPER('$skey')");
			$sdbq->execute();
			while(my $srow = $sdbq->fetchrow_hashref())
			{
				print IPTABLESSCRIPT "$ipbin -t filter -A FORWARD -s $row->{'address'}/$row->{'mask'} -d $srow->{'address'}/$srow->{'mask'} -j ACCEPT\n";
				print IPTABLESSCRIPT "$ipbin -t nat -A POSTROUTING -s $row->{'address'}/$row->{'mask'} -d $srow->{'address'}/$srow->{'mask'} -j ACCEPT\n";
				print IPTABLESSCRIPT "$ipbin -t nat -A PREROUTING -s $row->{'address'}/$row->{'mask'} -d $srow->{'address'}/$srow->{'mask'} -j ACCEPT\n";				
			}
		}
	}
}

foreach my $key (@networks)
{
	my $dbq = $dbase->prepare("SELECT inet_ntoa(address) AS address, mask FROM networks WHERE name = UPPER('$key')");
	$dbq->execute();
	while (my $row = $dbq->fetchrow_hashref())
	{
		my $sdbq = $dbase->prepare("SELECT inet_ntoa(ipaddr) AS ip, inet_ntoa(ipaddr_pub) AS pubip FROM nodes WHERE access = 1 ORDER BY ipaddr");
		$sdbq->execute();
		while(my $srow = $sdbq->fetchrow_hashref())
		{
			if(matchip($srow->{'ip'},$row->{'address'},$row->{'mask'}))
			{
				print IPTABLESSCRIPT "$ipbin -t filter -A FORWARD -s $srow->{'ip'} -j ACCEPT\n";
				print IPTABLESSCRIPT "$ipbin -t filter -A FORWARD -d $srow->{'ip'} -j ACCEPT\n";
				
				if(isprivate($srow->{'ip'}))
				{
					print IPTABLESSCRIPT "$ipbin -t nat -A POSTROUTING -s $srow->{'ip'} ";
					if($snataddr)
					{
						print IPTABLESSCRIPT "-j SNAT --to $snataddr\n";
					}
					elsif($srow->{'pubip'} eq '0.0.0.0')
					{
						print IPTABLESSCRIPT "-j MASQUERADE\n";
					}
					else
					{
						print IPTABLESSCRIPT "-j SNAT --to $srow->{'pubip'}\n";
					}
				}
			}
		}
	}
}
if($postscript)
{
	print IPTABLESSCRIPT "$postscript\n";
}
$dbase->disconnect();
close(IPTABLESSCRIPT);
chown $cuid, $cgid, $cfile or print "Warning! Unable to set owner of $cfile to $cuid.$cgid.\n";
chmod oct($cperm), $cfile or print "Warning! Unable to set permission $cperm to $cfile.\n";
