#!/usr/local/bin/perl
# Enable or disable the iptables rule

require './frox-lib.pl';
&foreign_require("firewall", "firewall-lib.pl");
$conf = &get_config();
$port = &find_value("Port", $conf);
&error_setup($text{'iptables_err'});
&ReadParse();

# Get the old rule
@tables = &firewall::get_iptables_save();
($nat) = grep { $_->{'name'} eq 'nat'} @tables;
if ($in{'rule'} ne "") {
	($rule) = $nat->{'rules'}->[$in{'rule'}];
	}

if ($in{'enabled'} && !$rule) {
	# Need to create
	gethostbyname($in{'net'}) ||
	    ($in{'net'} =~ /^([0-9\.]+)\/(\d+)$/ &&
	     &check_ipaddress($1) && $2 > 0 && $2 <= 32) ||
		&error($text{'iptables_enet'});
	$rule = { 'chain' => 'PREROUTING',
		  'j' => [ '', 'REDIRECT' ],
		  'p' => [ '', 'tcp' ],
		  'm' => [ '', 'tcp' ],
		  'dport' => [ '', 21 ],
		  'to-ports' => [ '', $port ],
		  's' => [ '', $in{'net'} ],
		  'cmt' => 'Forward FTP connections to Frox proxy' };
	push(@{$nat->{'rules'}}, $rule);
	$apply = 1;
	}
elsif (!$in{'enabled'} && $rule) {
	# Need to delete
	splice(@{$nat->{'rules'}}, $in{'rule'}, 1);
	$apply = 2;
	}
else {
	$apply = 0;
	}
if ($apply) {
	# Save and apply
	&lock_file($firewall::iptables_save_file);
	&firewall::save_table($nat);
	&unlock_file($firewall::iptables_save_file);
	if (defined(&firewall::apply_iptables)) {
		$err = &firewall::apply_iptables();
		}
	else {
		$out = &backquote_logged("cd / ; iptables-restore <$firewall::iptables_save_file 2>&1");
		$err = "<pre>$out</pre>" if ($?);
		}
	&error(&text('iptables_eapply', $err)) if ($err);
	&webmin_log("iptables", $apply);
	}

&redirect("");


